Search code examples
c++cpointersdeclaration

Placement of the asterisk in pointer declarations


I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.

How about these examples:

  1. int* test;
  2. int *test;
  3. int * test;
  4. int* test,test2;
  5. int *test,test2;
  6. int * test,test2;

Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.

The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?


Solution

  • 4, 5, and 6 are the same thing, only test is a pointer. If you want two pointers, you should use:

    int *test, *test2;
    

    Or, even better (to make everything clear):

    int* test;
    int* test2;