question about constant variable in c/c++

This is a discussion on question about constant variable in c/c++ within the C++ Programming forums, part of the General Programming Boards category; i have a question about constant variable in c/c++.The following is my code: Code: int main() { const int a ...

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    1

    question about constant variable in c/c++

    i have a question about constant variable in c/c++.The following is my code:

    Code:
    int main()
    {
            const int a = 10;
            int * p = (int*)&a;
            *p = 11;
    
            printf("the address of p = %p\n",p);
            printf("the address of a = %p\n",&a);
            printf("value of  a  =  %d\n",a);
            printf("value of *p = %d\n",*p);
    
            return 0;
    }
    And the output is :

    Code:
    the address of p = 0xbfecca1c
    the address of a = 0xbfecca1c
    value of  a  =  10
    value of *p = 11
    I don't know why variable "a" and "p" have the same address but their value are different?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Because you're a naughty boy right here:
    Code:
    int * p = (int*)&a;
    At that point the compiler can do what it wants. What it apparently wanted to do (and which it is allowed to do) is to go through and turn all the a's into 10's (sort of like pre-processing) without bothering to refer to the actual memory location.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Quote Originally Posted by fatshaw View Post
    Code:
            printf("the address of p = %p\n",p);
    That's not going to print the address of p. You'd need to use &p to print its address.

    Your code has undefined behaviour, any outcome is valid.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. constant being treated as 32-bit when variable is 64-bit
    By ulillillia in forum C Programming
    Replies: 12
    Last Post: 08-13-2010, 12:07 AM
  2. question regarding accessing variable values
    By do_kev in forum C Programming
    Replies: 2
    Last Post: 03-08-2008, 11:55 AM
  3. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 09:43 AM
  4. Variable Arguments Question
    By moonwalker in forum C Programming
    Replies: 8
    Last Post: 08-04-2002, 09:08 AM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 01:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21