0

consider the following C++ code:

char test='a';

test=test-32;

cout << "test: " << test << endl; //prints 'A'


test='a';

cout << "diff: " << test-32; //prints '65'

You can see that if I assign to test (my char variable) the value of test-32, it prints the Uppercase 'A' character. Instead if I just print the value of test-32, it seems to just print the difference between the ASCII code of the 'a' character and 32.

Could someone help to understand what's going on here? Maybe C++ automatically casts the ASCII code to the relative character when trying to assign it to a char variable?

ela
  • 325
  • 2
  • 10
  • In C and C++ types smaller than int get automatically promoted to int before being evaluated ***in an expression***. This explains your results. See the linked question for more information. `test-32` is an expression. – Sam Varshavchik Nov 27 '22 at 22:47
  • When you print a `char`, with cout you get the ascii value. 'a'-32 assigned to a char will print an 'A'. If you want to know the decimal value, assign it it to an int instead of a char. Or, as @SamVarshavchik points out, `std::cout << 'a' -'A'; ` is 32, the decimal value of the difference. – doug Nov 27 '22 at 22:49
  • A `char` is just an integer type like `int`. There is no difference. It stores integer values. Only the output functions will behave differently if they see a `char` type. Instead of printing the numeric value stored in the variable in decimal representation, they will translate the numeric value to a character according to a certain mapping called the execution character set encoding, which is usually ASCII or an extension of it. But as hinted by the duplicate when you do arithmetic the result is never a `char`, always an `int` or larger, due to promotion. – user17732522 Nov 27 '22 at 22:53
  • A character literal like `'a'` uses the same encoding in the opposite direction to translate characters into numeric values to store in the `char` object. – user17732522 Nov 27 '22 at 22:54
  • The result is `33` instead of `65` because you set `test` to `'A'`, not `'a'`. – user17732522 Nov 27 '22 at 22:55
  • 1
    Try `cout << "test: " << +test << endl;` – Eljay Nov 27 '22 at 23:10
  • @user17732522 You're right, sorry for the mistake – ela Nov 28 '22 at 02:36
  • Use `+` operator and you'll see the char being promoted to int. [Does the unary + operator have any practical use?](https://stackoverflow.com/a/14365849/995714), [What is the purpose of unary plus operator on char array?](https://stackoverflow.com/q/25701381/995714) – phuclv Nov 28 '22 at 03:29

0 Answers0