I made a super complicated explanation of pointers.

I can explain the *y thing. Both uses are actually consistent, but the reason you might not see it is because the C syntax for declarations is never taught accurately. The way C declarations are taught, the syntax is supposedly:

<type> <variable name>;

So declaring a variable named x with the type int is int x;. Thus to declare an int pointer we need a way to write that type. The designers supposedly decided to reuse * in a slightly different way and have the type 'pointer to int' written as int*. But this is not correct.

The syntax for a variable declaration is more like

<primitive type> <expression using desired variable name>;

Where the 'primitive type' is never "int *". The type must be one of the built-in types, or a typedef name, or a struct. Instead, everything else goes in the <expression> part. So the declaration int* x; actually splits up into a type int and an expression *x. What it means is "I would like to be able to write an expression *x and the result will be an int. The compiler then figures out that in order to make *x evaluate to an int, it has to make x be a pointer to an int.

Another example:

int (*(*foo)())[];

The compiler asks itself how to make the expression (*(*foo)())[] evaluate to an int. It figures out that (*(*foo)()) needs to evaluate to an array of int, which means that (*foo)() needs to evaluate to a pointer to an array of int, which means that *foo needs to evaluate to a function which returns a pointer to an array of int, which means that foo must be a pointer to a function which returns a pointer to an array of int.

There is some inconsistency. For example, when you declare a function int foo(int a, int b); obviously you can't write an expression: foo(int a, int b) and get an int. However, using C's original syntax, declaring a function is done like so: int foo(a, b); in which case foo(a, b) does evaluate to an int, assuming a and b are appropriately declared variables.


Arguably the expression based declaration syntax is confusing and was a mistake, and people teach C declarations inaccurately because it's simpler. However it does mean that mean that you also have to teach additional rules like 'never declare two variables on one line', in order to avoid mistakes like int* x, y;, and so on.

/r/cpp Thread Parent Link - imgur.com