I have a program like below and expect that:
with function
void myFunc1 ( const int *x)
==> I cannot change the value of at the memory location thatx
points to, but can change the memory location thatx
points to.with function
void myFunc2 ( int const *x)
==> I cannot change the location thatx
points to as it is a const pointer. But I could change the value at the memory location thatx
points to.
However, upon compiling the code, I don't see the difference between const int *x
vs int const *x
:
- in both function, the lines
*x=8
in both function return error. I didn't expect error frommyFunc2
because it is aconst
pointer, not a pointer to aconst
value. - in
myFunc1
, I expected to see value 5 aftermyFunc1
is close.
Could the experts here explain my 2 unexpected results above ? Here is my code:
#include "stdio.h"
int a = 5; // declared a global,
void myFunc1 ( const int *x) { // const parameter: pointer to a const int value.
// *x= 8; // error: assignment of read-only location ‘* x’ ==> cannot change the value at the location pointed by pointer. This is expected
printf("%d \n ", *x);
x = &a; // can change where the pointer point to.
// a is global and is not loss after closing myFunc2
printf("value in myFunc1: %d \n ", *x);
}
void myFunc2 ( int const *x) { // const parameter: const pointer, cannot change the address that x points to.
// *x= 8; // error: assignment of read-only location ‘* x’
printf("%d \n ", *x);
x = &a; // no compiling error here. This is not expected.
printf("value in myFunc2: %d \n ", *x);
}
int main() {
int *y;
int z = 6;
y = &z;
printf("value before myFunc1: %d \n", *y);
myFunc1(y);
printf("value after myFunc1: %d \n", *y); // expect to print 5. Result: print 6.
printf("value before myFunc2: %d \n", *y);
myFunc2(y);
printf("value after myFunc2: %d \n", *y); // expect to print 8 if the line *x=8 could be compiled . Result: print 6.
return 1;
}