This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: assigning to const int via pointer
- From: Ian Lance Taylor <ian at airs dot com>
- To: Joe Steeve <joe_steeve at gmx dot net>
- Cc: GCC Mailing list <gcc-help at gcc dot gnu dot org>
- Date: 30 Dec 2004 11:02:10 -0500
- Subject: Re: assigning to const int via pointer
- References: <87652k5lcy.fsf@proxy.tcenet>
Joe Steeve <joe_steeve@gmx.net> writes:
> The following code assigns a value to a `const int` via a
> pointer.,
>
> #include <stdio.h>
>
> int
> main()
> {
> const int x=5;
> int *ptr;
> ptr = &x;
> *ptr = 10;
> printf("%d",x);
> }
>
> The code gives `10` for the following compilation
>
> $gcc -o test test.c
>
> It gives `5` when using optimisations switches.,
>
> $gcc -o test -O2 test.c
>
> Feature or bug or any explanation for this?
When you declare that the variable is const, you are declaring that
the value does not change. When you do change it, you are using
undefined behaviour. When the compiler sees undefined behaviour, it
does not behave predictably.
ISO C99 6.7.3: "If an attempt is made to modify an object defined with
a const-qualified type through use of an lvalue with
non-const-qualified type, the behavior is undefined."
Ian