declaration of variables with same name as global,local and static

前端 未结 5 1540
北海茫月
北海茫月 2020-12-30 17:07

I have the following code snippet and I have to analyse what the output will be:

#include 

  void f(int d);

  int a = 1, b = 2, c = 3, d = 4         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 17:24

    In C/C++, the identifiers in a given scope shadow the identifiers in the outer scope from the point of declaration onwards.

    The following example demonstrates this:

    #include 
    
    const char a[] = "a";
    
    static const char b[] = "b";
    
    void test(const char * arg)
    {
       const char c[] = "c1";
       printf("1-. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
       const char a[] = "a1";
       static const char b[] = "b1";
       // arg is present in this scope, we can't redeclare it
       printf("1+. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
       {
          const char a[] = "a2";
          const char b[] = "b2";
          const char arg[] = "arg2";
          const char c[] = "c2";
          printf("2-. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
          {
             static const char a[] = "a3";
             const char b[] = "b3";
             static char arg[] = "arg3";
             static const char c[] = "c3";
             printf("3. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
          }
          printf("2+. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
       }
       printf("1++. a=%s b=%s c=%s arg=%s\n", a,b,c,arg);
    }
    
    int main(void)
    {
       test("arg");
       return 0;
    }
    

    Output:

    1-. a=a b=b c=c1 arg=arg
    1+. a=a1 b=b1 c=c1 arg=arg
    2-. a=a2 b=b2 c=c2 arg=arg2
    3. a=a3 b=b3 c=c3 arg=arg3
    2+. a=a2 b=b2 c=c2 arg=arg2
    1++. a=a1 b=b1 c=c1 arg=arg
    

提交回复
热议问题