char a = 'A';
int i = (int)a;
The cast is unnecessary. Assigning or initializing an object of a numeric type to a value of any other numeric type causes an implicit conversion.
The value stored in i
is whatever value your implementation uses to represent the character 'A'
. On almost all systems these days (except some IBM mainframes and maybe a few others), that value is going to be 65
.
char b = '18';
int j = b;
A character literal with more than one character is of type int
and has an implementation-defined value. It's likely that the value will be '1'<<8+'8'
, and that the conversion from char
to int
drop the high-order bits, leaving '8'
or 56
. But multi-character literals are something to be avoided. (This doesn't apply to escape sequences like '\n'
; though there are two characters between the single quotes, it represents a single character value.)
char c = 18;
int k = c;
char
is an integer type; it can easily hold the integer value 18
. Converting that value to int
just preserves the value. So both c
and k
are integer variables whose valie is 18
. Printing k
using
std::cout << k << "\n";
will print 18
, but printing c
using:
std::cout << c << "\n";
will print a non-printable control character (it happens to be Control-R).