5 ms·
The rule is misleading in cases like: int* arr[][10]; Spiral rule would state "arr is an array of pointers to arrays of 10 ints", where actually it would
by rfw 10y ago
The rule is misleading in cases like:
int* arr[][10];
Spiral rule would state "arr is an array of pointers to arrays of 10 ints", where actually it would be "arr is an array of array of 10 pointers to int".
Instead, when you write declarations, do it from right-to-left, e.g.:
char const* argv[];
"argv is an array of pointers to constant characters"
It doesn't help with reading, unfortunately.
- vostok 10y agoFor this reason I strongly prefer writing char const rather than const char Is there a reason to prefer the second version? It's a lot more popular in my experience.
- Spivak 10y agoIt's the difference between "declare a constant integer" and "declare an integer constant" and to me the former more accurately represents what you're doing since `const` is modifying `int`, `int` isn't modifying `const`.
- kccqzy 10y agoPutting const on the right makes more sense when you have pointers or references. Then you just always read from right to left: `int const ` is a pointer to constant integer whereas `int const` is a constant pointer to integer. Also your argument about which modifies which is strongly anglocentric: there are plenty of people whose native language puts modifiers after the things they modify.
- clusmore 10y agoI think the advice that helped me the most was "Declaration follows usage". int* arr[][10]; If you index twice into arr and then dereference, you'll get an int. So arr must be an array of array of pointer to int.
- convales 10y agoDeclaration follows usage is much more easier to follow than the artificial spiral rules, IMHO with a few typedefs the declaration follows usage can make things pretty simple.
- dllthomas 10y agoTo my mind that's one part of the reason the * belongs next to arr rather than next to int. The other part is `int* x, y`.