Bjarne Page 79 Need help understanding example

I have the Bjarne Stroustrup Programming Principles and Practice Using C++ 2nd edition. I am on page 79. 3.9.1 has an example...

char c = 'x';
int i1=c;
int i2='x';

Can someone explain to me how the book says both i1 and i2 has the value of 120? is the i1 and i2 saying i*1 and i*2? Left of the equals so be assignment... so math should be on the right. Or is i1 and i2 each a single variable? Where is everything getting the value? Is it referring back to a previous example on a previous page?
char is an integer type. You can do everything with a char that you can do with an int. Add, subtract, multiply, and so on. When you print a char it prints a character instead of a number but that is just because the << operator has been overloaded to treat char differently. If you convert the char into an int before printing you will see a number.

The value that represents character 'x' is 120.
Last edited on
closed account (E0p9LyTq)
What is the ASCII code for the 'x' character?
http://www.cplusplus.com/doc/ascii/

78 hex, 120 decimal.

i1 and i2 are variable names, not some obscure math.
http://www.cplusplus.com/doc/tutorial/variables/
i1 and i2 are just variable names. There is nothing funky going on with the identifiers (variable names) here, remember that an identifier is any series of characters starting with a letter or underscore and only containing letters, numbers and underscores. So if you have thing1 and thing2, the 1 and 2 are not something after the identifier, they are part of the identifier, part of the variable name.

What Stroustrup is demonstrating here (I think, I don't know the context of this example) is that values can be implicitly (that is, silently, without any steps or syntax or anything to tell the compiler to do it) converted to other variable types. You have a char, which is usually a small 8-bit integer and an int, which is usually a 32-bit or 64-bit integer type. What he's saying is it's valid to assign a smaller integer type to a larger integer type because it's large enough to hold the value. And that's it, there is no deeper meaning or trickery here.

As for the actual values, let's look at that again.

1
2
3
4
5
6
7
8
// The ASCII value of x is 120, this is the same as saying char c = 120;
char c = 'x';
// An int is big enough to hold a char, so you can say some_int = some_char
int i1 = c;
// And the same works for char literals like 'x', he's showing that 'x' is just an integer value
int i2 = 'x';
// And I'll add one, this one is also the same value as 'x'
int i3 = 120;
Topic archived. No new replies allowed.