1

My question here is regarding the allocation of memory space for the variable i.

#include <stdio.h>

int main(int argc, char **argv)
{

     switch(1)
    {
         int i=0; // this declaration is not reached
         printf("This line not reached\n");
         case 0:
             printf("this is case %d\n",i);
             break;
        case 1:
            printf("the value is %d\n",i);
            break;
       default:
       printf("this is the %d \n",i);
     }
    return 0;
}

So i is an automatic variable so it will be created once it is defined but entering the switch block the line for i definition is not executed. HOw can the program recognize and allocate space for the variable in printf function without encountering the variable i. thanks !

Sabrina
  • 1,460
  • 11
  • 23
  • 1
    I am not talking about initializtion I am talking about memory allocation the definition and printf is using i which was **never** defined !! Please explain to me . – Sabrina Feb 19 '17 at 12:10
  • 1
    I'm pretty sure the behavior of this program is undefined, so a compiler is free to do whatever. – StoryTeller - Unslander Monica Feb 19 '17 at 12:14
  • Please @StoryTeller how can the variable in printf is executed with i but i never has been defined (no memory allocation) – Sabrina Feb 19 '17 at 12:15
  • It was defined. It just remains uninitialized. Once you declared it at the beginning of the scope, it's introduced into it. You can tell that by being able name it as an argument to printf. The tricky part, is the the initialization of this variable cannot ever happen, since all execution paths jump to a point after it. – StoryTeller - Unslander Monica Feb 19 '17 at 12:17
  • If you are curious, you can compile it with a [C++ compiler](http://coliru.stacked-crooked.com/a/304c0c3395404ce9) where *it will* result in an error. Since in C++ the lifetime of a variable and it's initialization are intimately tied, like your intuition tells you it should be. – StoryTeller - Unslander Monica Feb 19 '17 at 12:20
  • still cannot understand how can it be if the line not executed :/ – Sabrina Feb 19 '17 at 13:05
  • 1
    Take a step back, and remove the initialization. Just write `int i;`. Then would you agree that there is a variable `i` in the scope of the switch that is uninitialized? Remember taht `case` labels are nothing more than a conditional jump into the middle of scope. But a scope and the variables within are defined by the pair of curly braces. – StoryTeller - Unslander Monica Feb 19 '17 at 13:11
  • @StoryTeller thanks now I got it. – Sabrina Feb 21 '17 at 02:23

0 Answers0