Question:
Find the output of the following C code?
Rama
2012-02-08 02:40:51 UTC
include
int main()
{
int a=1;
switch(a)
{ int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf("b is %d\n",b);
break;
}
return 0;
}

I knew that the int b=20; wont be executed but still i have a doubt that why the output show s 856. I thought that might be a garbage value. But even I close the program and reopen and execute that the result is 856. Is there any specific reason for that?
Five answers:
Obeida Ghazal
2012-02-08 04:06:49 UTC
"Case statements are only 'labels'. This means the compiler will interpret this as a jump directly to the label.The problem here is one of scope. Your curly brackets define the scope as everything inside the 'switch' statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it." [1]
husoski
2012-02-08 11:30:15 UTC
Garbage doesn't mean random. It just means that the results aren't predicted by the standard, and *may* not be the same from run to run.



In a typical implementation, local variables are stored on the stack and what's in an uninitialized variable is whatever was left on the stack from some earlier use. In this case, it might have been the system code that parses the command line arguments before calling your main() function, or some other run-time initialization.
AnalProgrammer
2012-02-08 11:31:09 UTC
The answer is that the results are unpredictable and this is compiler related.

856 is a number because you are printing a number (%d). That does not mean that the garbage started out as a number though. Without looking at the memory in that location you cannot easily work out what garbage you have.



Have fun.
duongvalo
2012-02-08 11:23:22 UTC
include

int main()

{

int a=1, b=20;

switch(a)

{ //int b=20;

case 1: printf("b is %d\n",b);

....

???
2012-02-08 11:26:59 UTC
You can't possibly get any output from this program. It does not compile.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...