Re: UB ??

From: Alwyn (alwyn_at_blueyonder.co.uk)
Date: 02/17/05


Date: Thu, 17 Feb 2005 13:01:53 +0000

On Thu, 17 Feb 2005 03:58:00 -0800, ranjeet wrote:
>
> Below are my some observation which did not follwed my excpectation
> as it was stated in the FAQS,
>
>
> int main () {
>
> const int i = 2; // Means it is not writable i.e it is in Read only memory.
> int *i_ptr; // Declare the poiter of int type.
> i_ptr = &i; // Assingning the address of the i.

My C compiler gives a warning for this. Didn't you get one?

If you really need to do this, you should use a cast.

> *i_ptr = 3;

It is illegal to alter a 'const' variable. If you declare something
'const', you are promising that you won't change it. Unfortunately, a
compiler is not always able to enforce this rule.

> printf("%u, %u, %d, %d", &i, ptr, i, *ptr);

<snip>

> Now how this is possible that same address is having the two diffrent
> values ?? at the same time.

If you do something illegal, as above, your program is not guaranteed to
work as expected. It's what 'undefined behaviour' means. There is a lot of
undefined behaviour in C that the compiler cannot prevent. Then the user
has to do his or her best to keep to the rules, which is not always easy.

Alwyn



Relevant Pages

  • Re: Writing single bits to a file
    ... The 'const' keyword provides the same kind of benefit that prototypes ... enabling the compiler to warn you if it detects the fact that you ... I had not gone and more correctly fixed up the precedence heirarchy (unary ... I like to implement scripting languages for breakfast ...
    (comp.lang.c)
  • Re: const
    ... > const modifiers, ... willing to remove the const'ness with a cast, ... I don't know how good a cross-file compiler could be - it would have to be ... it's a guarantee by the programmer. ...
    (comp.programming)
  • Re: compilation warning with const parameter
    ... into a const pointer to that element, ... The warning is thus correct: ... Compilers are required to produce diagnostics if constraints ... A compiler is not required to stop compiling upon detecting something ...
    (comp.lang.c)
  • Re: Index a #define string
    ... In this case, i wouldn't use an array myself but a const char * const, but ... should one make it of static storage? ... If they were on the stack, where do you think their values ... You mean that the compiler optimises it out. ...
    (comp.lang.cpp)
  • Re: List<> of struct with property. Cannot change value of property. why?
    ... temporary), the compiler could complain and say: ... Well, IMHO the compiler could easily provide the same warning today, without the "const" keyword. ... Relying on the "const" keyword to enable a warning wouldn't have been a good idea in C++, because you'd get a lot of false positives due to the large amount of code that is "const" without using "const". ...
    (microsoft.public.dotnet.languages.csharp)