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

前端 未结 5 1520
北海茫月
北海茫月 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:40

    This is related to C's identifier scopes. The scope of a declaration is the region of the C program over which that declaration is visible. There are six scopes:

    • Top level identifiers: extends from the declaration point to the end of the source program file
    • Formal parameters in a function definiton: extends to the end of the function body
    • Formal parameters in function prototypes
    • Block (local) identifiers: extends up to the end of the block
    • Statement labels
    • Preprocessor macros

    What happens in your program is known as overloading of names - a situation in which the same identifier may be associated to more than one program entity at a time. There are 5 overloading classes in C (aka namespaces):

    • Preprocessor macro names
    • Statement labels
    • Structure, union and enumeration tags
    • Component names
    • Other names

    In C, declarations at the beginning of a block can hide declarations outside the block. For one declaration to hide another, the declared identifiers must be the same, must belong to the same overloading class, and must be declared in two distinct scopes, one of which contains the other.

    With this in mind, in your code, local a and c hide global a and c in main(), and a in f() hides global a. All other references are manipulating the global variables.

提交回复
热议问题