Reputation: 1003
scrolling through http://git.suckless.org/st/plain/st.c I stumbled upon
#define LEN(a) (sizeof(a) / sizeof(a)[0])
I know precompiler magic is hard, and my C aint the best
but it makes me wonder if the parens at the end make sense - shouldn't it be something like
#define LEN(a) (sizeof(a) / sizeof((a)[0]))
Upvotes: 1
Views: 130
Reputation: 11438
The sizeof
operator doesn't really need parenthesis when the operand is a left-side expression instead of a type, so your parenthesis at the second sizeof
are not needed, as this one doesn't expect a type (because of the trailing [0]
). This LEN
macro seems to be used to get the size of a statically defined vector.
For example:
int v[10];
LEN(v) will expand to (sizeof(v)/sizeof(v)[0])
And (v)[0]
is the same as v[0]
so the second sizeof is actually something like sizeof v[0]
which is valid use of sizeof
(no parenthesis needed)
A well-known (at least here at Stack Overflow) example of a sizeof
that doesn't needing parenthesis is:
int *v;
v=malloc(10*sizeof *v);
To get a dynamically defined 10 element vector. Note that the previous LEN
macro won't work here.
Upvotes: 2