Naming: Why should named constants be all uppercase in C++/Java?

前端 未结 15 1778
情歌与酒
情歌与酒 2020-12-15 16:13

I know, that for C++ and Java it is a well established naming convention, that constants should be written all uppercase, with underscores to separate words. Like this (Java

15条回答
  •  半阙折子戏
    2020-12-15 16:40

    I can imagine that initially, back in the C days, people would implement "constants" symbolically, using the pre-processor:

    typedef unsigned int Color;
    #define BACKGROUND_COLOR 0xffffff
    

    Such "constants" are just prettified literals, and as such they don't behave quite as variables. You can't, for example, take the adress of such a "constant":

    Color *p = &BACKGROUND_COLOR; // Breaks!
    

    For this reason, it makes sense to have them "stand out", as they're really not just "variables you can't change".

提交回复
热议问题