Character/ASCII - Question

I am fairly new to C++ and still learning.

I understand the first code is casting a char into an interger. But I don’t understand the second one? Is it ment to be a function or? Can someone please help me understand thanks.

1
2
3
4
5
6
7
8
9
10

cout << (int)'a' << endl;    

cout << int('a');


Result: 
97
97
Different syntax for the same cast. I think they are pretty much equivalent. Both are C-style casts.

Alternatively, you could do a C++-style cast: static_cast<int>('a') :-)

As an aside, there is no guarantee that your input string is encoded in ASCII. Could be, e.g., Latin-1 or UTF-8.
Last edited on
L2 casts an 'a' (type char) to type int

L4 creates a temporary int with a value of 'a'.
> But I don’t understand the second one? Is it ment to be a function or?

The functional cast expression int('a') is exactly equivalent to the C-style cast expression (int)'a'.
as a side note, char is already a 1 byte int.
cout is 'smart' and prints a symbol when it sees type char. for most everything else, you don't need the cast, eg
for(int something = 42, char c = 0; c < 100; c++) //fine without casts
something *= c; //ok without casts.

and so on.
copypasta wrote:
I am fairly new to C++ and still learning.

There is a free online C++ tutorial website that might help in learning C++, Learn C++:
https://www.learncpp.com/
Topic archived. No new replies allowed.