Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping scoped variable initialization with goto not producing the desired output

Tags:

c

goto

#include <stdio.h>

int main()
{
    int a = 10;
    goto inside;
    {
        int a = 20;
        {
            inside:
            printf("%d",a);
        }
    }
}

Why does it print output as 0, not as 10? Even if it looks for nearest scope ie. int a = 20 which is not executed clearly. The memory contains only int a = 10; so why 0 here?

like image 265
Albert Singh Avatar asked Aug 06 '20 04:08

Albert Singh


1 Answers

At the point of the printf call, the name a refers to the second variable of that name, the one that's initialized to 20. The outer a, the one initialized to 10, is hidden. There's no reason for the printf to print 10.

The goto statement skips over the initialization of the inner a, so it's never initialized to 20. Space is allocated for it, but its value is arbitrary garbage. The 0 being printed is the contents of the inner a. It could have been anything.

like image 100
Keith Thompson Avatar answered Oct 19 '22 17:10

Keith Thompson