search

Home  >  Q&A  >  body text

C++/C语言中static const 和 const的区别

代码如下 :

static const int NUM = 1000;
const int ARRAY_LENGTH = 10;
  1. 想知道加不加 static 有什么区别吗 ?

  2. 如果我想将这个常量的使用范围限制在只在该文件中使用, 除了放在类中, 还有什么别的办法吗?

PHPzPHPz2803 days ago563

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 14:33:13

    If a global variable is modified by static, it is only visible in this file and cannot be used by other files

    Answer your two questions in one go~

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:33:13

    1. static global variables are private for files. If not added, other files can also reference

    2. Just add static

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:33:13

    1. Writing outside the function means that it is visible in the current source file (to be precise, the .o object file generated by compilation, because visibility is actually the concept of the linker), which is an internal link. If you don't write it, it will be an external link, and you can use extern to reference this variable in other source files.
    a.cpp

    static const int A = 0;
    const int B = 0;
    

    b.cpp

    extern const int A;  // 会发生链接错误
    extern const int B;  // 正确,多数是写在a.h里然后include
    

    Written in a function means it is a static variable. Calling this function multiple times will share the same memory, instead of generating new ones on the stack.

    void foo()
    {
        static const int A = 0;    // 多次调用foo,&A不变。
        const int B = 0;           // 多次调用foo,&B不固定。
    }
    

    2. There is a method. For C++, it is recommended to use anonymous space instead of static to make the variables visible in this file.

    namespace {
        const int MAX_BUFFER_SIZE=200;
    }
    

    reply
    0
  • Cancelreply