Scope of a variable outside main in C

前端 未结 7 619
深忆病人
深忆病人 2020-12-15 21:41

Consider the code:

#include 

int x;

int main (void) 
{ }

The value of x is 0 inside main

7条回答
  •  孤街浪徒
    2020-12-15 22:33

    This feels like a homework question but I'll bite anyhow.

    To use the x you have defined here in a class or function from another file, you would use

    extern int x;
    

    above your usage of the x variable (like in the header) then you can use x just like you would in main(). extern tells the compiler that you are using a variable that is defined/instantiated elsewhere.

    If you want it to exist before the main is run, then you use static which is handled prior to main() running. In other words it loads the memory space with variables prior to kicking off any processing (in main.)

    As to why it is 0 on startup, that is likely just your compiler giving it a base value. Not all compilers do this, unless I am mistaken, many will just give you whatever was in the memory space allocated to x which could be anything. In other words they give you the memory complete with whatever data (or partial data) was in it beforehand.

提交回复
热议问题