Simple question - what is a "char" variable used for.

Jul 25, 2012 at 3:32pm
I've recently purchased "Beginning C++ through game programming third edition" (recommend as a beginner starting C++ btw) And it was telling about some variable types such as bool, double, float etc. Which I all get fine, but I don't get char variable; there's an table for the VT's and when it comes to "char" it says 256 character values. What does it mean?
Jul 25, 2012 at 3:48pm
Char is a one-byte integer type. If it is singed or unsigned depends on the compiler. It's often used to store characters. Char literals 'x' have type char. String literals are arrays of char.
Last edited on Jul 25, 2012 at 3:49pm
Jul 25, 2012 at 3:54pm
To add to Peter's answer, since a char is one byte, and you will typically be working on machines which have 8 bits to a byte, and each of those 8 bits can take a value of zero or one, there are 2 to-the-power-of 8 possible values the char can have, which is 256; this is where your it says 256 character values comes from.
Last edited on Jul 25, 2012 at 3:54pm
Jul 26, 2012 at 9:35pm
Thanks guy, that makes it more clear.
Would it be possible for you to show do an example in which you would include the "char" variable?
Jul 26, 2012 at 10:43pm
1
2
3
4
5
6
7
8
9
10
11
12
cout << "Continue? y/n" << endl;
char input;
cin >> input;

if (input == 'y')
{
  // do something
}
else if (input == 'n')
{
  // do something else
}


Jul 26, 2012 at 10:55pm
Char is also displayed as it's ASCII representation:
1
2
3
4
5
int i = 65;
char ch = 65;

cout << i << endl; // Displays 65
cout << ch << endl; // Displays A 


Edit: about line 2: Better to have done char ch = 'A';
Last edited on Jul 26, 2012 at 10:57pm
Jul 27, 2012 at 12:37pm
Now I fully understand it :D Thanks, Guys :D
Topic archived. No new replies allowed.