Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is one of the misconceptions:

> sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T.

That's a misconception I had and I've never run into a problem. What's a platform where sizeof works differently?

Also, what's the reasoning for sizeof to be an operator rather than a function?



See https://stackoverflow.com/questions/2098149/what-platforms-h.... As for `sizeof` being an operator, well, C doesn't have generics, so it has no choice but to make `sizeof` somehow special.

If you don't want to bother supporting platforms where byte is not 8-bit (a reasonable choice I would say), use `int8_t`/`uint8_t` instead. Those types won't exist on platforms that don't have 8-bit bytes.


> If you don't want to bother supporting platforms where byte is not 8-bit (a reasonable choice I would say), use `int8_t`/`uint8_t` instead. Those types won't exist on platforms that don't have 8-bit bytes.

You'll have the issue that, as one of the commenters explained above, `char` is its own thing, independent and separate from `signed char` and `unsigned char` to say nothing of `int8_t` and `uint8_t`. This means that while you can use your own thing for your own functions you can not do so if your values have to interact with libc functions (or most of the ecosystem at large).

If you only want to support platforms using 8-bit chars, you should check CHAR_BIT. That is actually reliable and correct.


> C doesn't have generics, so it has no choice but to make `sizeof` somehow special

It could have used a different syntax though. Ada has a special syntax for compile-time inquiries like this, so there's no way to confuse them with function calls. Ada calls these attributes.

https://en.wikibooks.org/wiki/Ada_Programming/Attributes#Lan...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: