I got the output as "a: 8", can any one answer why is it so??Code:main(){ int a=0010; printf("a: %d\n", a); return 0; }
I got the output as "a: 8", can any one answer why is it so??Code:main(){ int a=0010; printf("a: %d\n", a); return 0; }
Because 0010 (or more simply: 010) specifies 8 in octal.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
A leading zero indicates to the compiler that the number is an octal number. You then print it's decimal equivalent. octal 010 -> decimal 8.
I got output as b is <some garbage value>, why is it so?Code:int main(){ int a=1; switch(a){ int b=20; case 1: printf("b is %d\n",b); break; default: printf("default b is:\t%d", b); break; } return 0; }
What are you trying to do?Originally Posted by vpshastry
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Compile it with some warnings.Code:$ gcc -Wall bar.c bar.c: In function ‘main’: bar.c:6: warning: ‘b’ may be used uninitialized in this function
case labels are thinly disguised goto labels. As such, a 'goto' from the switch to case 1 will MISS the initialisation of b.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
because the declaration of b is skipped by your case statement. You need to declare b before your switch statement and then you can assign specific values inside your case statements
EDIT:
Code:#include <stdio.h> int main(void){ int a=1,b; switch(a){ case 1: b=20; printf("b is %d",b); break; default: b = 10; printf("default is %d",b); break; } getchar(); return(0); }
Why is it considered an error when compiled with g++ instead of gcc ? (without -Werror)Originally Posted by Salem
Does missing the initialization also mean missing the declaration in C++ and not C?
In switch statement control should move directly to case statement skipping any other statements. Here it should skip int b=20; and show an error as b undeclared. Why is it not so?
Because what is skipped is the initialisation of b. b is still declared to be in scope at the point of use. I would not be too concerned about the exact behaviour specified by the standard (though in this case I referred to the text of C99) as I would identify such code as containing a potential problem and fix it.Originally Posted by vpshastry
Last edited by laserlight; 09-16-2011 at 01:00 PM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)