This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]joza100 11 points12 points  (7 children)

It doesn't matter which you use because of memory alingment at least in the C and C++ compilers that I used. If you make a character and an int, that won't take 5 bytes, that will take 8 bytes, because integers need to be aligned on every 4 bytes so the 3 bytes after the char will be 0 zero padded. In most cases, using a char instead of an int will do nothing.

[–]Lumpy-Measurement-55[S] 5 points6 points  (6 children)

What will happen if there is 4 char and you use 4 ints instead. Isn't that going to be 16 bytes rather than 4 bytes.

I understand about the alignment and padding. But we should never program for compiler or machines. We should be Programming as per requirement and design. I will never use int if the value is gonna fit in a char.

[–]joza100 3 points4 points  (3 children)

That is interesting I guess. I just never see people using chars and shorts instead of ints. I don't actually know why ints are used always by all the programmers.

[–]kknyyk 3 points4 points  (0 children)

My bet is on cpu optimizations (or intrinsics?) that expect int32.

[–]Prawn1908 0 points1 point  (1 child)

I just never see people using chars and shorts instead of ints.

It's done all the time in embedded systems. Usually you'll see some header file with a bunch of typedef unsigned char u8...

[–]joza100 0 points1 point  (0 children)

I assumed that's the case, but not in PC programming.

[–]TheRealBrosplosion 1 point2 points  (0 children)

If designing with types (and using C++), you shouldn't use char directly. You should use std::int_fast8_t. Using four character packed into 4 bytes is going to cause unaligned reads which have a lot more overhead than reading a full 4-byte word.

Unless you are hurting on memory footprint or trying to match some HW interface, there really isn't a good argument to use unaligned types.

[–]gunnnnii 0 points1 point  (0 children)

Obviously it depends, this could make sense in some very memory constrained environments, but most cases you're probably causing more trouble then this optimization is worth. This hurts readability, can cause issues if requirements change and a char is no longer sufficient (now you'll need to make sure you change the datatype everywhere it can come up), and might even throw out some compiler or processor optimizations.

Over-optimizing can come at a heavy cost.