0

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);
   }
Vijay S B
  • 1,251
  • 1
  • 13
  • 24
  • 3
    The second one leads to *undefined behavior*. You use a pointer to non-constant `int` to modify a constant `int`. A good compiler should warn about it, and if it doesn't then you should turn on more warnings. – Some programmer dude Oct 07 '16 at 05:39
  • 1
    warning: initialization discards qualifiers from pointer target type – Vijay S B Oct 07 '16 at 05:42
  • So the case2 should be int const *ptr=&x to get the same behavior as we got in case1. – Vijay S B Oct 07 '16 at 05:48

1 Answers1

3

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765