when i run this program "x is an integer " is printed. according to ansi is it supposed to be printed?Code:#include <stdio.h> int main() { int x=1; switch (x) { case 1 : printf( "x = 1\n" ); default : printf( "x is an integer\n" ); } }
when i run this program "x is an integer " is printed. according to ansi is it supposed to be printed?Code:#include <stdio.h> int main() { int x=1; switch (x) { case 1 : printf( "x = 1\n" ); default : printf( "x is an integer\n" ); } }
You should put a break statement at the end of every case unless you want it to run into the next case.
Code:case 1 : printf( "x = 1\n" ); break;
Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie
what i am asking is whether the 'default ' statement runs always or runs only when no other case is true.
As XSquared said you need to put break; at the end of 'case 1' in order to prevent the 'default' statement to run if 'case 1' is correct. If you don't put it, then if 'case 1' is correct, also the 'default' will run, thus making the 'default' statement always run. Just use the break keyword when using switch.
In your case, always, as described by other posts. When all others are false, it will always execute. (Unless you don't provide a default case, then nothing happens.)Originally posted by modec
what i am asking is whether the 'default ' statement runs always or runs only when no other case is true.
But, as illustrated, since you left out the break keyword, in your case, it will always execute.
Quzah.
Hope is the first step on the road to disappointment.