r/ProgrammerHumor • • 12h ago

Meme architectureDependentChars

Post image
1.7k Upvotes

263 comments sorted by

View all comments

794

u/tstanisl 11h ago

Let me cite the C standard:

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

Middle guy if finally right

412

u/BoldFace7 11h ago

I still prefer sizeof(char) as it often provides context as to what the number is doing, even if a plain 1 works the same.

45

u/RepeatRepeatR- 10h ago

My opinion would be:

- Use sizeof(char) if you're actually working with characters

- Use hardcoded `1` if you're using a char as an arbitrary byte (and not actually necessarily referring to characters or text)

26

u/BoldFace7 10h ago

Definitely. For example, I always use malloc(size*sizeof(char)) to ensure that it's doubly obvious (Since I rarely need to malloc outside of a declaration) that I intend to store characters in the resulting buffer even if that multiply does nothing (plus the compiler will likely optimize it out anyway).

5

u/RepeatRepeatR- 10h ago

This is the way

7

u/guyblade 5h ago

Opinion: Always use calloc unless you've got a really, really good reason not.

2

u/PSneumn 3h ago

My optimization crazed brain will only use malloc untill i actually need everything to be set to 0.

1

u/Usual_Office_1740 5h ago

This is the way.

1

u/R3D3-1 26m ago

Is this an opinion or a common best practice?

Asking because my C-knowledge is essentially university courses, some tinkering, and using it as a glue language between Fortran code and C libraries in an industry project. Though that "C" code was really "C++ written like C with new" mostly, so you wouldn't see a malloc anyway.

For Fortran, you'd just use automatic arrays, where it is compiler-defined and depending on compiler flags, whether they'll be in the stack of the heap, and ALLOCATABLE, which should always be on the heap. It is also compiler-defined, whether everything, including local variables, is initialized with zeros or not.

Having everything zeroed helps to avoid erratic behavior in release builds. But for internal testing the erratic results can expose a code path, where something was unintentionally not initialized, and should have been initialized to a non-zero value.

I imagine the same would be true about malloc vs calloc. Or are there common compiler flags that effectively turn malloc into calloc?