4 ms·
Also, `#define countof(a) (sizeof(a) / sizeof(*(a)))` is unsafe since the arg is evaluated twice.
by oh_sigh 3y ago
Also, `#define countof(a) (sizeof(a) / sizeof(*(a)))` is unsafe since the arg is evaluated twice.
- david2ndaccount 3y agoArguments to sizeof aren’t actually evaluated (except for variably-modified-types, AKA VLAs, but don’t use those).
- uecker 3y agoPlease use those. They are useful, make code clearer, improve bounds checking, ... Don't let attackers influence the size of a buffer (neither for VLAs nor for heap allocations).
- badsectoracula 3y agoThis is a very common macro to get static array lengths and i'm not sure there is any other way to do the same thing (i.e. give a static array, get back the number of items in it) in any other way.
- f33d5173 3y agoThe arg is expanded twice but evaluated zero times, since sizeof gives the size of its argument type without executing anything.
- Izkata 3y agocountof(foo()) looks like foo() is only called once, but would actually be called twice. That's what GP is talking about, it's evaluated twice after the expansion when the code is actually running, not during the expansion.
- deleted 3y ago[deleted]
- uecker 3y agoIt is not evaluated for regular arrays. It is evaluated for arrays with variable size, you need to be careful a bit. But this is rarely happens to be a problem. The general rule for sizeof is to apply it only to variable names or directly to typenames.
- tpush 3y agoAgain no, foo isn't called at all since countof() only uses its argument in a sizeof expression.