3 ms·
This style rests on the premise that C declaration syntax is: <type> <space> <name> It isn't, and using the style is misleading people to think that it is.
by Peaker 14y ago
This style rests on the premise that C declaration syntax is:
<type> <space> <name>
It isn't, and using the style is misleading people to think that it is.
You can't write:
int[10] a;
You write:
int a[10];
Basically any type that involves more than a base-type and a pointer is going to fail to work with that style, and then you will lose uniformity as well.
There's actually a pretty good reason for the way C syntax is: The declaration and use syntax are virtually identical, and the precedence rules are identical. It's nice to only have to learn that once.
The fact the * before the variable looks like dereferencing is intentional, you're supposed to read this:
int *x;
as: "Declare the dereference of x to be an int".
And this:
int (*(*x)(void))[10];
As "The dereference of x is a function of void, the dereference of which is an array of 10 ints".
- pixie_ 14y agoThe declaration and use syntax of pointers is not 'virtually identical.' int* a; could be used to set int* b = a; or int c = * a; or int* d = &a; Also for arrays it's unfortunate the syntax is like it is, because int a[10];, is of course a pointer and would be a bit more intuitive in the form of int[] a = new int[10]; Also you say * before the variable 'looks like dereferencing is intentional.' but is it really? what's your source?
- Peaker 14y agoYou are misunderstanding. I'll start from what you said about arrays: > because int a[10];, is of course a pointer This is a common misconception about C. int a[10] defines an array, not a pointer. typeof(a) is int[10], and not (int ptr). The thing is, whenever you take the value of an array in C, it is degraded to a pointer to the array's first element, and this confuses people to no end that arrays are pointers. For example, if we declare: int a[10]; int *b; Then sizeof(a) and sizeof(b) are very different. typeof(&a) is pointer-to-int[10], whereas typeof(&b) is pointer-to-pointer-to-int. void f(int (*x)[10]) { ... } If you call: f(&a); // will type-check f(&b); // will not So the syntax for declaring arrays is fine, and when you declare an array, no pointer is being declared at all. This is C syntax for type declarations: <base type> <type declaration here> The "<type declaration here>" part uses virtually the same syntax as use syntax. For example, if x is a pointer to a function that returns a pointer to an array of floats, you could reach a float via this syntax: (*(*x)())[1] You could declare x using this syntax: float (*(*x)())[10]; The main differences are: * Array size instead of index * There's no requirement to dereference a function pointer to call it, but there is a requirement to use the dereference syntax to declare it. * Array values can be used as pointers to their first elements (due to the automatic degradation), but must be declared as arrays.