5

The variable i is declared const but still I am able to change the value with a pointer to the memory location to it. How is it possible?

int main()
{

    const int i = 11;
    int *ip = &i;
    *ip=100;
    printf("%d\n",*ip);
    printf("%d\n",i);
}

When I compile, I get this warning :

test.c: In function ‘main’:
test.c:11: warning: initialization discards qualifiers from pointer target type

Output is this

100
100
1
  • 2
    You're discarding the const qualifer, consult your compiler documentation if you want warnings to be errors. Commented Feb 21, 2012 at 3:51

5 Answers 5

9

The const is not a request to the compiler to make it impossible to change that variable. Rather, it is a promise to the compiler that you won't. If you break your promise, your program is allowed to do anything at all, including crash.

For example, if I compile your example code using gcc with the -O2 optimisation level, the output is:

100
11

The compiler is allowed to place a const qualified variable in read-only memory, but it doesn't have to (apart from anything else, some environments don't implement any such thing). In particular, it is almost always impractical for automatic ("local") variables to be placed in read-only memory.

If you change the declaration of of i to:

static const int i = 11;

then you may well find that the program now crashes at runtime.

Sign up to request clarification or add additional context in comments.

3 Comments

It's not actually the static which crashes the program. It's the incorrect cast. That's the bug, and the precise consequences of a bug can depend on many minute factors such as this one static. And on another compiler, you may see the crash only if there is no static; the result of a bug is hard to predict.
It's not actually the cast the crashes the program - the cast is allowed, if somewhat dubious. It's modifying the object that was declared with a const qualifier that's the bug.
static is related to the crash. In modern systems, static const variables (or const variables at file scope) can be allocated on a read-only segment, and attempting to write to such an address will cause a protection fault.
8

const is a compile-time feature.
It doesn't prevent you from shooting yourself in the foot; that's what the warning is for.

3 Comments

const is not necessarily only a compile-time feature. In my environment, if I make the variable i in the above example static, then the program crashes at runtime.
There is a difference between const and static. const allows the compiler to generate warnings. static allows the compiler to replace the value with a literal number or place it in read only memory or anything else it likes
@Martin Beckett: static alone does not allow the compiler to place it in read-only memory - in principle it is only const that allows that, but in practice const must be combined with static for this effect because it is simply impractical to do so for automatic variables. const alone variables can be replaced by literals at their point of use, even automatic ones.
3

Though it may be a warning in C, this is a compiler error in C++.

If you somehow manage to cast this const int in C/C++, then it may result in undefined behavior. The reason is, you are casting a number literal (i.e. const int i =11;) from const to a mutable value.

There is difference between what your code shows and following sequence:

int x = 11;    // x is modifiable
const int i = x;
int *ip = (int*)(&i);  // ok
*ip=100;

2 Comments

Whether it's a warning or an error depends on the flexibility of the compiler, not the language. It's wrong in both C and C++.
@ChrisLutz, for C it might be dependable (that's why I used "may be"), however, for C++ it should definitely be a compiler error, because of breaking const correctness.
2

A const-qualified object cannot be modified. If such an attempt is made, the program exhibits undefined behavior (C99 6.7.3.5). (Your program is incorrect.)

More on const: an object which is not declared as const can be modified, but not by the use of const-qualified lvalues. This is most evident when pointers are involved. For example, consider the declarations:

int i = 10;
int *p1 = &i;
const int *p2 = &i;

It is possible to modify i through i itself and through p1, but not through p2. This means that *p2 can evaluate to different values, even though p2 points to a const object, because other statements may change the object pointed to by p2 (an aliasing pointer, as in the example).

However, if i itself was const-qualified, then attempting to modify it through p1 will yield undefined behavior (as your code does).

Comments

0

It's not the attempt to modify i that causes your program's behavior to be undefined, it's the initialization of ip.

const int i = 11;
int *ip = &i;

&i is of type const int*. ip is of type int*. Attempting to initialize an int* with a const int* value is a constraint violation. A conforming implementation is requires to issue a diagnostic; once it's done that, it may or may not reject the translation unit. If it accepts it, the C standard says nothing about the resulting program's behavior.

Compilers that accept such things typically generate code equivalent to a conversion from const int* to int*, making the declaration effectively equivalent to:

int *ip = (int*)&i;

but the language doesn't require this behavior.

Don't ignore warnings.

(Note that with the cast, the code doesn't violate a constraint; then the behavior of the following

*ip = 100;

is undefined because it attempts to modify a const-qualified object.)

gcc in particular has a lot of cases where diagnostics for constraint violations are handled (by default) as warnings rather than fatal errors. I personally dislike that about gcc; it lets through too much bad code.

(Your program's behavior is also undefined because you call printf without a visible declaration; add #include <stdio.h>. And int main() should be int main(void).)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.