Is there any practical situation when we should store numerical values in char type variables in C++?
Asked
Active
Viewed 105 times
0
-
2If you need a variable that's a single byte, then yes. Remember, `char`s are `int`s, just with a smaller range. – 3Dave Oct 30 '20 at 14:11
-
Are you talking about char or a c-string? Many people new to the language (who are being taught c with classes instead of modern c++ which has std::string) mistakenly say char when they mean a c-string. – drescherjm Oct 30 '20 at 14:12
-
1Sure, why not ? 8 bit audio samples, pixel component values, H/W register values - there are many things that have a <= 8 bit range. – Paul R Oct 30 '20 at 14:12
-
1@PaulR Those typically use either `unsigned char` or `signed char`. Why use `char` for those over the others? – eerorika Oct 30 '20 at 14:14
-
When there's an existing library or platform interface that uses `char` and we want to match it? – Useless Oct 30 '20 at 14:17
-
1@eerorika: yes, I was assuming the OP was referring to types which are of width char, but the question is rather vague and lacking in detail. Ideally of course you would use `uint8_t` *et al*. – Paul R Oct 30 '20 at 14:18
-
1fwiw, `char` always store numerical values. Assuming ascii encoding, there is literally no difference between storing an `'A'` or storing `65` in a `char` – 463035818_is_not_an_ai Oct 30 '20 at 15:24
1 Answers
5
If you need lots of integers each of which would fit into a byte, and you're constrained in memory, you can use signed char
or unsigned char
to store them. Whether or not plain char
is signed depends on the implementation, so you'll want to avoid that. To be more expressive, you can use int8_t
and uint8_t
which are defined in <cstdint>
(and <stdint.h>
though it's deprecated). Those are usually just a typedef for signed char
and unsigned char
anyway, so be careful when printing their numeric values.

Aykhan Hagverdili
- 28,141
- 6
- 41
- 93
-
1Note, however, that `int8_t` and `uint8_t` will not exist on a system that does not have an 8-bit integer type, so use of these types should be reserved for programs that require **exactly** 8 bits. `int_least8_t` and `uint_least8_t` are a better choice if the goal is just to minimize memory usage. – Pete Becker Oct 30 '20 at 16:39
-
@PeteBecker that's correct. Related: [Is CHAR_BIT ever > 8?](https://stackoverflow.com/q/32091992/10147399) – Aykhan Hagverdili Oct 30 '20 at 16:42
-
Yes, `CHAR_BIT` is greater than 8 for some hardware. I don't remember what it was, but there was a line of mainframes with 36-bit registers, and they could be sub-divided into 9-bit registers, so `char` was naturally 9 bits wide. These days, some DSP chips don't have anything smaller than 32 bits, so `char` is 32 bits wide. – Pete Becker Oct 30 '20 at 16:49