Find the answer to your Linux question:
Results 1 to 3 of 3
Hi All, Can someone explain the concept for the below program? Program: +++++++ Code: #include <stdio.h> int main() { const int num = 5; int &ref = (int &)num; ref ...
  1. #1
    Just Joined!
    Join Date
    Oct 2008
    Posts
    7

    Question Reference and const...

    Hi All,

    Can someone explain the concept for the below program?

    Program:

    +++++++


    Code:
    #include <stdio.h>
    
     
    
    int main()
    
    {
    
      const int num = 5;
    
      int &ref = (int &)num;
    
      ref = ref + 2;
    
      printf("num addr:%x ref addr:%x,\n",&num,&ref);
    
      printf("num value=%x ref value=%x\n",num,ref);
    
    }

    Output:

    ++++++



    num addr:bfb403b4 ref addr:bfb403b4,

    num value=5 ref value=7



    Same address but different values?

  2. #2
    Just Joined!
    Join Date
    Jun 2010
    Posts
    1

    C program

    Did you compile the program and got output. I compiled the program and got the errors.

  3. #3
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    This is invalid code. You have declared 'num' as a const int (constant integer), yet you have cast it as a reference to a non-constant integer with the line:
    Code:
    int& ref = (int&) num;
    Then you try to modify ref, which is just an ALIAS for the num variable, but which since it is a constant, cannot be modified. Bad, bad, bad! If num was NOT const, then this would work, but you could also leave off the casting cruft. IE, try this:
    Code:
    #include <stdio.h>
    
     
    
    int main(void)
    {
      int num = 5;
      int& ref = num;
    
      ref = ref + 2;
    
      printf("num addr:%x ref addr:%x,\n", &num, &ref);
    
      printf("num value=%d ref value=%d\n", num, ref);
    }
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...