Const in C gives unpredictable result

Possible duplicate:
constants and pointers in C

I have this little piece of code. I am using the gcc compiler:

#include <stdio.h> int main() { const int a=10; int *d; d=&a; *d=30; printf("%d %d\n",a,*d); return 0; } 

It gives a warning when compiling:

"assign qualifiers from target pointer type"

But there is no mistake. Output: 30 30

Then is it worth it to ignore the goal of supporting a constant variable whose value is fixed during program execution (please correct me if I am wrong)?

+4
source share
3 answers

const not a guarantee. This is only a promise. Promises can be broken. The compiler warns when this happens, but is not required otherwise to prevent this, as there may be times when traversing a constant can be useful.

+4
source

You should not do this, and the compiler gives you this warning for some reason. However, C / C ++ will allow you to do anything you want. You must write clean code.

You can reflect the constant of this value using:

 int const * d = &a; 

Then, changing what d indicates, gives warnings and errors.

0
source

Source: https://habr.com/ru/post/1443853/


All Articles