-1

This code snippet was taken from an online C Programming Quiz.

https://www.youtube.com/watch?v=5sOZ7l2it2I

Please help me understand this code. Apparently it prints a garbage value. Here we have a local variable var, which hides the scope of the global variable var. I assumed that the local variable var is initialized with the value of the global variable var, the rvalue of the global var is copied into the local var. I understand that from that point on, the name var in the code now refers to the local var. So printing the local var should also print 5. But this is not the case. The program prints a garbage value. This means that the local var was uninitialized or some kind of error happened during initialization of the local var. What is going on here? Is this an issue of undefined behavior?

#include <stdio.h>
int var = 5;
int main() {
  int var = var;
  printf("%d", var);
}
Galaxy
  • 2,363
  • 2
  • 25
  • 59

1 Answers1

3

Grossly speaking, your int var = var; inside main is equivalent to :

int var; // this var is now in the current scope but is uninitialized
var = var; // assign the garbage value from var to var.

So the global var is ignored, and the local var keeps its garbage value (since it is assigned to itself).

Read about lexical scoping. Check the C11 standard n1570 (notably its ยง6.2.1).

BTW, a good enough compiler might warn you, if you ask for all warnings and debug info (so gcc -Wall -Wextra -g with GCC; actually it does not for gcc 8 on Debian/Linux ...).

As a rule of thumb, better give longer and descriptive names to global variables, and always avoid naming local (block-scope) automatic variables like global or static (file-scope) ones.

Regarding undefined behavior, read Lattner's blog and be scared of UB.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547