-2

I have initialized a global variable with value 5, and then initialized a local variable with the same name.

When I execute the below code using gcc compiler

//Code 1
#include<stdio.h>

int var = 5;
int main()
{
  int var = var;
  printf("%d",var);
}

the output is 0

If I modify the code as follows and compile with gcc,

//Code 2
#include<stdio.h>

int var = 5;
int main()
{
  int v = var;
  printf("%d %d",v, var);
}

the output is 5 5

If I modify the code as follows and compile with g++,

//Code 3 
#include<stdio.h>

int var = 5;
int main()
{
  int var = var;
  printf("%d %d",var, ::var);
}

the output is 0 5

I think that the value 0 is because the compiler is initializing it to default value(https://stackoverflow.com/a/1597491)

I have tried using gcc -g Code_1 and running gdb on the output binary, and inserted a breakpoint on

line no 4(int var = 5;)

line no 7(int var = var;)

line no 8(printf("%d",var);)

But on running the program the execution stops at line no 8, and print var outputs $1 = 0. When I step out of code 0x00007ffff7e07223 in __libc_start_main () from /usr/lib/libc.so.6, the output of print var is 5.

Please help me with my following queries:

  1. Why is the program printing value 0 and neither reporting an error nor using the global value?

  2. i. Does C have scope resolution operator ::, like C++?

    ii. If no, then how can we use local and global variable with same name?

    iii. How can I check the value of both global and local var, using gdb?

  3. Why doesn't the gdb encounter a breakpoint before main()?

Community
  • 1
  • 1

1 Answers1

2

I think that the value 0 is because the compiler is initializing it to default value

No. The local var is used as its own initialiser. Since its value is indeterminate before initialisation, the behaviour of the program is undefined.

  1. Why is the program printing value 0 and neither reporting an error nor using the global value?

The behaviour is undefined.

  1. i. Does C have scope resolution operator ::, like C++?

No.

ii. If no, then how can we use local and global variable with same name?

There is no equivalent operator in C. You cannot access both variables in a single expression.

eerorika
  • 232,697
  • 12
  • 197
  • 326