1

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])) 
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I had no idea one could use sizeof w/o parens, and I've never seen the sizeof pointer notation like this. but everything makes sense when i think of sizeof as an operator and not a function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.