Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Definition Ignore in C [duplicate]

Tags:

c

variables

Code:

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;
}

Output: It prints some garbage value for b when does the declaration of b takes place here Why b is not initialized with 20 here???

like image 936
Luv Avatar asked Dec 01 '25 05:12

Luv


2 Answers

Because memory will be allocated for int b but when the application is run "b = 20" will never be evaluated.

This is because your switch-statement will jump down to either case 1:1 or default:, skipping the statement in question - thus b will be uninitialized and undefined behavior is invoked.


The following two questions (with their accepted answers) will be of even further aid in your quest searching for answers:

  • How can a variable be used when it's definition is bypassed? 2

  • Why can't variables be declared in a switch statement?


Turning your compiler warnings/errors to a higher level will hopefully provide you with this information when trying to compile your source.

Below is what gcc says about the matter;

foo.cpp:6:10: error: jump to case label [-fpermissive]
foo.cpp:5:9: error:   crosses initialization of 'int b'

1 since int a will always be 1 (one) it will always jump here.

2 most relevant out of the two links, answered by me.

like image 127
Filip Roséen - refp Avatar answered Dec 03 '25 20:12

Filip Roséen - refp


Switch statements only evaluate portions of the code inside them, and you can't put code at the top and expect it to get evaluated by every case component. You need to put the b initialization higher in the program above the switch statement. If you really need to do it locally, do it in a separate set of braces:

Code:

int main()  
{
  int a=1;
  /* other stuff */
  {
    int b=20;
    switch(a)
    {

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

      default:
      printf("b is %d\n",b);
      break;
    }
  }
  /* other stuff... */
  return 0;
}
like image 20
Wes Hardaker Avatar answered Dec 03 '25 20:12

Wes Hardaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!