Char and Int?

closed account (LN7oGNh0)
I know what they are, but why use char for an integer when you could use int? With int, you can just assign a number to it, but with char you have to use an integer cast. Is char able to do some things with numbers better than int?

Thanks.
I know what they are, but why use char for an integer when you could use int?


2 reasons:

1) chars typically consume less memory (1 byte per char instead of 4 or 8 bytes per int). This is largely a nonissue since the extra 3 or so bytes is pretty insignificat... but if you have an array of 100,000 elements, then it can add up.

2) You might intentionally want the variable to be clipped (truncated) to a smaller size. Usually this is a very bad thing, but it can be desirable in some situations (for example, when writing an emulator that simulates 8-bit hardware, you would want math to "roll over" once you cross the 8 bit boundary).

With int, you can just assign a number to it, but with char you have to use an integer cast.


You do not have to cast integers to chars. chars can accept integral values normally:

1
2
3
4
5
6
7
char foo = 5;
foo += 16;

if(foo == 21)
{
  cout << "this will print";
}


The only time you'd need to cast is when printing it, since chars are printed differently from other integers.
Sometimes it might be useful. Let's say you were writing some kind of program that dealt with hex characters.. 0-9 & A-F (0-15). A char in this case would work better than an integer since the int can't store the letter parts of hex values.
closed account (LN7oGNh0)
Thank you for good answers!
Topic archived. No new replies allowed.