Why should the C language use as few global variables as possible

Source: Internet
Author: User

When a program is linked, the linker only cares about functions and global variables, and the linker recognizes them as symbols for linking. Note that function overloading in high-level languages is only a syntactic sugar, essentially a different function

Strong symbols: Functions and initialized global variables
Weak symbol: Uninitialized global variable

    • Multiple strong symbols are not allowed. as follows, the compiler will error
//a.c中定义的全局变量iint i = 10;//b.c中定义的全局变量idouble i = 10;
    • If you have 1 strong symbols and multiple weak symbols, select strong symbols. As below, will not error
//a.c中定义的全局变量iint i = 10;//b.c中定义的全局变量idouble i;
    • If there are multiple weak symbols, randomly select one from them. As below, will not error
//a.c中定义的全局变量iint i;//b.c中定义的全局变量double i;
    • It can be seen that the misuse of global variables is dangerous, so you should try to avoid global variables, or use static adornments.

Why should the C language use as few global variables as possible

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.