Thread: Issue with const int

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    22

    Issue with const int

    Hi,
    I tried the following program :
    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
            const int PI=3;
            int *ptr;
            printf("Original Value of PI = %d\n",PI);
            ptr=&PI;
            *ptr=4;
            printf("Value of PI after modification = %d\n",PI);
            return 0;
    }
    Though PI has been made const int i am still able to modify its value through a pointer. Why is that?

    Thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you ignore warnings (either by ignoring the output frome the compiler or not enabling the generation in the first place), then const is not enforced in C.

    If you compile the same code in C++, then it will complain that you can't do the conversion from const int * to int *.

    With gcc, you get a warning if you use -Wall:
    Quote Originally Posted by GCC
    c.c:9: warning: assignment discards qualifiers from pointer target type
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Even if you can subvert the compiler to allow you to modify const, don't do it. The compiler may not heed you or you can get strange results.
    Plus it would defy the whole purpose of const.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes & Collections
    By Max_Payne in forum C++ Programming
    Replies: 7
    Last Post: 12-11-2007, 01:06 PM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  4. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM