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 ...
- 08-03-2011 #1Just Joined!
- Join Date
- Oct 2008
- Posts
- 7
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?
- 08-03-2011 #2Just 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.
- 08-08-2011 #3Linux Guru
- 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:
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:int& ref = (int&) num;
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!


Reply With Quote