8

C: global variable and local variable of the same name

 2 years ago
source link: https://www.codesd.com/item/c-global-variable-and-local-variable-of-the-same-name.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C: global variable and local variable of the same name

advertisements

Code:

#include <stdio.h>

int var = 20;
int main()
{
   int var = var;
   printf("%d\n", var);
   return 0;
}

GCC outputs garbage value in this code. My doubt is, this should output "20".

Explanation: Whenever we assigns value to any global/local variable, the first instruction is to the computer is save the assigned value to a register and then put that into memory. So, according to me, when the compiler comes to "int var = var" it should first save value 20 to a specific register. And after that it will save it to local variable. And then after global variable should go out of scope. Yeah, it contradicts the statement that, name of variable is assigned firstly than its value. So, int var makes the global var variable out of scope and makes local variable assigns it itself, That is equivalent to uninitialized local variable.


int var = var;

is undefined behavior. It is self assignment with an uninitialized value.

Tags gcc

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK