Question on this program!

closed account (yR9wb7Xj)
Hi can someone explain to me what the static_cast char function did in my program? I did everything else up to the static_cast <char> and I looked up the internet how to use it, but I found an example that provided just the static_cast answer and I copy that to my program, but I'm confuse on what it's doing. This is just for practice, I'm done with college for the semester and I'm trying to practice as much as possible to get better at problem solving.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
int main()
{

	int num;
	char a = 'A', b= 'B', c = 'C', z = 'Z';

	cout << "Input a number between 0 & 35." << endl;
	cin >> num;

	if(num <=9)
		cout << num << endl;
	else if(num >=10  && num <= 35)
		cout << static_cast<char>('A' + num -10) << endl;
	else
		cout << "You were suppose to choose a number between 0 & 35. \n You chose one above that number." << endl;










	return 0;

}
Last edited on
static_cast is a way of converting one type into another. When you add or subtract an int with a char you get an int, so 'A' + num -10 is an int. You don't want to print an integer, so you have to change the type of the integer to a char and that's why static_cast<char> is used here.
Last edited on
The cout << static_cast<char>('A' + num -10); could be split into three statements:
1
2
3
auto X = ('A' + num - 10);
char Y = static_cast<char>(X);
cout << Y;

What is the type of X? The C++11 keyword 'auto' means that the X has an exact type and the compiler knows it.

The type of X is not char.

There are many overloads for operator <<. The stream formats the output depending on the type of the right-hand operand. Value with type char produces a character. Value of X produces something else. This is easy to demonstrate:
1
2
3
4
auto X = ('A' + num - 10);
cout << "X = '"<< X << "'\n";
char Y = static_cast<char>(X);
cout << "Y = '"<< Y << "'\n";



The static_cast creates a (temporary) value that has the template type (char) from the value (X), if there is a type conversion operator that can produce a char from the type of X.

See http://en.cppreference.com/w/cpp/language/static_cast
closed account (yR9wb7Xj)
That makes sense thank you!
Topic archived. No new replies allowed.