0

From the below code how to print global value:

Conditions are that, we must not use extern keyword, should not comment the local initialization & should not shift the printf function.

#include <stdio.h>

int a = 20;

int main()
{
    int a = 10;
    printf("%d",a);
}

I expect the output of 20.

  • 2
    [int a=20;main(){int *ga=&a;int a=10;printf("%d\n",*gaa);}](https://ideone.com/kulrQH) -- not use extern: check -- not comment local: check -- not shift printf: check – pmg May 01 '19 at 13:21
  • 1
    You should avoid name conflicts like this in first place. – Jabberwocky May 01 '19 at 13:29
  • You should avoid global variables – Ed Heal May 01 '19 at 13:35
  • In C, there isn’t a sensible way to do it, unless you add `#define a z` before the definition in `main()` and `#undef a` after it or something equally silly. In C++, the scope resolution operator might help, but would modify the `printf()` statement. Whatever technique your faculty have in mind is unlikely to be useful professionally; writing clear code is the primary requirement. – Jonathan Leffler May 01 '19 at 14:48

1 Answers1

2

extern will not help as you have another variable with the same name in most inner scope (in this case scope of function main). So you will see this variable instead if the global one.

You need to rename one of those variables.

int a=20;
int main()
{
    int b=10;
    printf("%d",a);
}

you may have more inner scopes:

int a=20;
int main()
{
    int a=10;
    {   
        int a = 5;
        {
            int a = 2;
            printf("%d",a);
        }
    }
}

and the result is 2

0___________
  • 60,014
  • 4
  • 34
  • 74