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

前端 未结 15 1659
情歌与酒
情歌与酒 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:38

    Probably you are right. Computers and compilers (especially) were not so fast as today.

    Joel Spolsky mentioned in one of his essays how impressed he was with compilation time of new version of Turbo Pascal.

    I remember when compilation of not too big program (10-20KLOC) with overlays in Turbo Pascal 5.0 on PC XT 10MHz took about 20 minutes...

    I suppose that waiting for compilation to detect error was not acceptable.

    And convention like that helps to avoid errors and wasted time during broken compilation.

    0 讨论(0)
  • 2020-12-15 16:38

    Actually most C++ naming guidelines (including ISO, Boost, Sutter & Stroustrup and Google) strongly discourages naming constants with all caps. This is because macros also use all caps and they can be littered all over in header files potentially creating strange behaviors. People still use all caps anyway because they learn from old C/K&R or old legacy code. However in Modern C++ new code you should avoid using all caps for anything except macros.

    My pet theory for why all caps exists at all is that on very old machines, code was being entered directly in machine code using numeric keypads. When assembly language arrived on the scene, it only used all caps because keyboard at that time weren't standardized and some keyboards were limited ,for example, using same numeric keypads to enter alphabets like in feature phones. This got then carried over to many early languages like BASIC which is all caps everything. When actual terminals became available and keyboards started to get standardized, people started using mixed cases without reservations and all caps got reserved for something that is rare in occurrence like constants compared to functions and variables.

    Most C++ guidelines now agree on using "k" as prefix for constant followed by name with either underscore or CamelCase. I personally prefer kCameCase because it easily allows to distinguish from variables which are named with under_scores.

    const float kFixedRadius = 3.141;
    
    0 讨论(0)
  • 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".

    0 讨论(0)
提交回复
热议问题