Why does std::cout automatically convert the char variable I defined into the corresponding int from ASCII table? For example, in the code below, variable test is a char, but it prints out the integer 3.
1 2 3
int main(){
char test = 51;
cout << test;}
Also, why does the following code give a value of 1? I know that single quote is used for single char, but it seems like it always outputs the last digit of the number in a single quote char. Thanks for helping.
int(test) creates a temporary int, +test promotes a char variable, to be interpreted as an int.
For all practical purposes doing either really doesn't matter too much. A char is a simple Plain Old Data type, so creating one, even if a temporary, is not a terribly expensive operation.
I simply prefer to not create temporaries if it can be avoided. +temp is a round-about alternative to (int) temp or static_cast<int> (temp).
All three tell the compiler you want a char to be treated as an int for the operation.