0

I have two questions with usage of const as an argument in C:-

  1. Can a pointer be modified when we pass "const p" as an input argument to a static BOOL and void functions. In which case it is possible? If not possible how can we do it with the following example?*

for example:-

main() { int const *p = 1; BOOL(*p); } static BOOL(const *p) { *p = 10; printf("*p = %d\n", x); void(*p); } ------------------------------------ void(*p) { A(*p); } A(*p) { *p = 0; } 

**2. Do we have any difference between "CONST int p" and "int const p" ?

1
  • do you know the diff between: int* const ptr and const int* ptr or even better const int* const ptr Commented Jul 21, 2020 at 6:22

3 Answers 3

3

There are 3 different cases in related to pointer and const:

1)pointer to const value: This is a pointer to point to a const value and should put const keyword before type. For example:

 const int var = 7; const int *ptr = &var; 

2)const pointer: This type of pointer just initialize in declaration and can not modify. To declare should put const keyword between * and name of pointer. for example:

 int var = 7; int *const ptr = &var; 

3)const pointer to const value: This type of pointer is const pointer to point to const value. To declare should put const keyword before type and after *. For example:

 int var = 5; const int *const ptr = &var; 
Sign up to request clarification or add additional context in comments.

Comments

2

CV qualifier is left-associative, const T is the same as T const.

For example

  1. const T *p = T const *p, so p is mutable, but *p is immutable
  2. T * const p, p is immutable, while *p is mutable
  3. T const * const p, both p and *p are immutable

2 Comments

in the 3rd case you mean: const T * const p, both p and *p are immutable (OR) T const * const p, both p and *p are immutable ?
@SasankSaiSujanAdapa both are the same, as mentioned in 1
0

this here: const int *ptr is a pointer to const value meaning you can not change the value of the variable the pointer is pointing to...

const int value = 5; const int* ptr = &value; *ptr = 0; //<-- this is invalid 

now, this here: int *const ptr is a const pointer meaning the address value hold by the pointer can not be changed

int value1 = 0; int value2 = 1; int* const ptr = &value1; ptr = &value2; // <-- this is invalid 

Comments