Why is the C++ variable declaration syntax inconsistent?

前端 未结 5 1763
醉梦人生
醉梦人生 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:13

    It's because of the C heritage. The * modifier applies to the variable in C. So the C++ designers made & to apply to the variable as well by analogy, since they couldn't change the first without breaking C compatibility. Same is true for the array syntax too:

    int anInt, *aPointerToInt, anArrayOfInt[100];
    

    In The Design and Evolution of C++ Bjarne Stroustrup says he wasn't happy with this but had to accept it for C compatibility. He was unhappy with this in particular:

    int *a[10];
    

    It's not clear from the declaration if a is a pointer to an array or an array of pointers (it's an array of pointers, you need brackets to override).

    Of course, you can always use a typedef to clean things up a little.

提交回复
热议问题