Why is the C++ variable declaration syntax inconsistent?

前端 未结 5 1756
醉梦人生
醉梦人生 2021-01-11 10:33

when I declare C++ variables, I do it like this:

int a,b,c,d;

or

string strA,strB,strC,strD;

I.e., first

5条回答
  •  天命终不由人
    2021-01-11 11:20

    The best answer I've seen as to why things like * apply to variables and not to types is the idea that declaration should follow use.

    Basically, how you declare a variable should look similar to how you use a variable.

    For example,

    int *a, b;
    ...
    *a = 42;
    b = 314159;
    

    ...the use of a and b looks similar to the declaration of a and b.

    There's even a citation for this behavior from Dennis Ritchie, one of the creators of C:

    Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear...In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration.

    • Dennis Ritchie, The Development of the C Language. History of Programming Languages-II ed. Thomas J. Bergin, Jr. and Richard G. Gibson, Jr. ACM Press (New York) and Addison-Wesley (Reading, Mass), 1996; ISBN 0-201-89502-1.

提交回复
热议问题