0

I want to convert a char value to an int. I am playing with following code snippets:

#include <iostream>
using namespace std;

int main() {
    char a = 'A';
    int i = (int)a;
    //cout<<i<<endl; OUTPUT is 65 (True)

    char b = '18';
    int j = b;
    //cout<<j<<endl; OUTPUT is 56 (HOW?)

    char c = 18;
    int k = c;
    //cout<<c<<endl; OUTPUT is empty
    //cout<<k<<endl; OUTPUT is 18 (Is this a valid conversion?)

    return 0;
}

I want the third conversion, and I got correct output i.e 18. But is this a valid conversion? Can anyone please explain the above outputs and their strategies?

user2754070
  • 509
  • 1
  • 7
  • 16

2 Answers2

3
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).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
1
char b = '18';
int j = b;

b, in this case a char of '18' doesn't have a very consistent meaning, and has implementation-dependent behaviour. In your case it appears to get translated to ascii value 56 (equivalent to what you would get from char b = '8').

char c = 18;
int k = c;

c holds character value 18, and it's perfectly valid to convert to an int. However, it might not display very much if you display as a character. It's a non-printing control character.

Baldrick
  • 11,712
  • 2
  • 31
  • 35