1

My code:

#include <stdio.h>
main()
{
    const int x = 10;
    int *p;
    p=&x;
    *p=20;
    printf("Value at p: %d \n",*p);
    printf("Value at x: %d", x);
}

The output I get is:

Value at p: 20
Value at x: 20

Thus, the value of a constant variable is changed. Is this one of the disadvantages of using pointers?

user2350631
  • 61
  • 1
  • 5
  • 1
    C doesn't prevent you from doing dumb things like this. You do get a warning from the compiler though: `const.c:9: warning: assignment discards qualifiers from pointer target type` – MatthewD May 06 '13 at 01:33
  • `#include "stdio.h"` => `#include ` – Elazar May 06 '13 at 01:36
  • Note that depending on the compiler and optimizations enabled, you could get have in your output "Value at x: 10". – fbafelipe May 06 '13 at 01:49
  • The only useful `const` in C that I can see is in parameters. – Jack May 06 '13 at 05:01

5 Answers5

2

You used a int* to point to a const int. you should get:

 error: invalid conversion from ‘const int*’ to ‘int*’

when you do:

p = &x;

You probably needs to update your compiler, a decent compiler should have told you this error or at least gave you warning about this.

taocp
  • 23,276
  • 10
  • 49
  • 62
0

Please check the following error message:

error: invalid conversion from ‘const int*’ to ‘int*’

const int, int const, const int *, int const *, please see this post: const int = int const?

It's just how you use it.

Community
  • 1
  • 1
gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
0

That's because you are using the C language in the wrong way and the compiler let you compile this code while giving only a warning

warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]

And there are answers for that on SO, such as warning: assignment discards qualifiers from pointer target type

Community
  • 1
  • 1
user2348816
  • 532
  • 4
  • 9
0

Any decent compiler will tell you that you are discarding the const qualifier.

C assumes that the programmer is always right, hence it's your choice to ignore your compiler's warnings or not. As usual, this is not a disadvantage as long as you know what you're doing!

cmc
  • 2,061
  • 1
  • 19
  • 18
0

As other answers have noted, writing a program to try to modify a const qualified variable like this results in a program that has undefined behaviour. This means that your program can do anything at all - as an example of this, when I compile your program with optimisations enabled, I see this output:

Value at p: 20
Value at x: 10

..and if I add the static qualifier to the variable x then the program crashes at runtime.

caf
  • 233,326
  • 40
  • 323
  • 462