Vijay S B Vijay S B - 2 months ago 17
C Question

Constant int incement

Consider below two cases.
case1: compiler error --> error: increment of read-only variable ‘x’

#include<stdio.h>
main()
{
const int x=5;
printf("%d",++x);
}


case2: Ran successfully with output 6. why?

#include<stdio.h>
main()
{
const int x=5;
int *ptr=&x;
++(*ptr);
printf("%d",x);
}

AnT AnT
Answer

int *ptr=&x; is a constraint violation, i.e. an "error", invalid code. C language does not support implicit conversion of const int * type to int * type. Your compiler surely issued a diagnostic message for this.

After that diagnostic message your program's behavior is no longer defined by C language, assuming your compiler somehow agreed to compile it. Many C compilers can be configured to refuse to compile this code, even if they accept it in default mode.

You could force the conversion by using a cast

int *ptr = (int *) &x;

This would get rid of the above constraint violation. The compilers would now have to accept your code (with some caveats). But after that modification, the attempt to do ++*ptr would trigger undefined behavior, because it is an attempt to modify a const object.