[SOLVED]Explain the execution of this program | Sololearn: Learn to code for FREE!

+4

[SOLVED]Explain the execution of this program

In this code the int X is initialized 2 times so I was expecting the 2nd initiation value to be value of variable X..but it seems like compiler is considering both X different... Why those { } are making so much difference... I'm not declaring a function even so that there would be a difference in local variables.. Please explain how it works.. Edit:12 sep 2019 <code link removed , adding code in description > Code : #include <stdio.h> int main() { int X=20; { int X=10; printf("%d",X); } printf("%d",X); return 0; }

4/5/2019 5:49:12 AM

🇮🇳Omkar🕉

2 Answers

New Answer

+4

Within the {} is a different scope, that can have its own x. That also happens in other scoped operations, like when you declare variables in a for loop or in an if block. If there is no inner x, the outer one will be taken; if there's an inner one, it will be a separate 'local' x that is 'forgotten' as soon as the code leaves the curlies.

+1

There are two types of variables in C. Local variables and Global variables. Variables defined in between {} are called local variables. Variables defined inside any function are local variables. Its scope is within the {}(braces). Variable defined outside the main function is called a global variable. It is accessible in the whole program till compiler do not find any local variable accessible at that place. In the given program, the compiler first reads global variable X, but as soon as it enters the main function, the accessibility of local variable has greater precedence. So it is printed. As soon as the compiler comes out of the main function, the scope of the local variable ends up. So global variable X is printed. Please keep in mind that, I am not talking about storage types here.