Albert Singh
Albert Singh

Reputation: 71

Skipping scoped variable initialization with goto not producing the desired output

#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?

Upvotes: 7

Views: 138

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263257

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.

Upvotes: 7

Related Questions