Is it common programming practice to use unsigned
, signed
, long
, long long
, etc in our C++ programs? I have noticed that that’s what my textbook does, but my lecturer doesn’t do that. Does it have benefits to it in terms of program effectiveness, or a recommendation for programmers?
I have tried to use the method in the textbook, but I end up falling behind in my work because our lecturer codes the simple way and I always try to keep up with the textbook, but it takes me a while to catch up.
7
Yes, it’s quite common. For small math, int
alone does what you need, but when you get to more advanced usage (e.g. bit-twiddling, bit-masks, etc.), larger numbers, performance optimization, etc., people will use stuff other than plain int
. That said, unsigned
/long
/long long
(and int
for that matter) are portability nightmares, so modern idiomatic C and C++ tend to use fixed width, least width, or fast-width integer types to guarantee a specific number of available bits (so if the same code is compiled on machines with a different concept of int
[I’ve personally worked with systems where int
is 16, 32, or 64 bits], it’ll still have at least 32 bits of precision when you use int_least32_t
).
Your teacher is likely sticking to int
because simple arithmetic on “human comprehensible” numbers doesn’t need anything bigger on modern desktop/laptop class machines with 32 bit int
(the representable range runs from roughly -2.1 billion to 2.1 billion, and toy problems for new programmers don’t need more than that). In more advanced classes, the distinction between signed and unsigned types will become more important, as will correctly sizing your types, but for now, it just doesn’t matter.
There is one exception to this rule. signed
is basically only used in conjunction with char
(which by default has implementation-defined signedness, and is distinct from both unsigned char
and signed char
, even if it behaves the same as one of them); it’s redundant on anything else. So if you need a signed
char
-sized value to do math with, you have to use signed char
. 99% of the time though, you’d just use int8_t
or int_least8_t
in that case, but it’s something you might see in older code (or code written by people who know the problems with plain char
, but not the better solutions).
9