Does it matter where I place the asterisk when declaring pointers in C++?

前端 未结 3 1191
予麋鹿
予麋鹿 2020-12-20 18:08

I\'m just learning C++ and from all the example code I have looked at over the past few days I am having a hard time understanding where the pointer should be placed.

<
相关标签:
3条回答
  • 2020-12-20 18:51

    Algough * is sometimes placed next to the variable it really does belong to the type declaration. So the following:

    SomeType *x, *y;
    

    really means

    SomeType *x;
    SomeType *y;
    

    The same goes with &. Additionally *, const and & are applied in the order of their proximity to the declared type. For example:

    const SomeType * const *&x = ...;
    

    would mean: reference to pointer to a const pointer to const SomeType. const can be placed both before and after the type name. The const before the type is applied before all the modifiers after the type. Also note that this is not allowed:

    const SomeType const x = ...;
    

    as it would essentially mean const const SomeType, which doesn't make much sense.

    0 讨论(0)
  • 2020-12-20 19:11

    no difference, but you must pay attention that if you write:

    char* x, y;
    

    only x is a pointer (the first variable declared) and you should reference them this way:

    x = new (char);
    *x = 'a';
    y = 'b';
    
    0 讨论(0)
  • 2020-12-20 19:13

    There's no difference. They're exactly the same.

    You can choose to write it however you like. Typically, C++ programmers place the asterisk next to the type, while it is more common for C programmers to place the asterisk next to the name of the variable.

    The only pitfall to be aware of is when you declare multiple variables on a single line (which you really shouldn't do anyway, if not for precisely this reason). For example, in the following statement, only variable x is declared as a pointer:

    char* x, y;
    

    Compare that with the following, which makes it much more clear which variables are pointers:

    char *x, y;
    

    As best I can tell, the third syntax emerged as a poor compromise between the two leading options. Instead of placing the asterisk next to one or the other, someone decided to place it in the middle, which is about the only place it decidedly does not belong.

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