Defining global constant in C++

前端 未结 10 1916
梦如初夏
梦如初夏 2020-11-29 16:44

I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file:

  1. #define GLOBAL_
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 17:30

    If it's going to be a constant then you should mark it as a constant - that's why 2 is bad in my opinion.

    The compiler can use the const nature of the value to expand some of the maths, and indeed other operations that use the value.

    The choice between 5 and 6 - hmm; 5 just feels better to me.

    In 6) the value is unnecessarily detached from it's declaration.

    I typically would have one or more of these headers that only defines constants etc within them, and then no other 'clever' stuff - nice lightweight headers that can easily be included anywhere.

提交回复
热议问题