debendra nath tiwary
debendra nath tiwary

Reputation: 73

Is it safe to cast a character type to an integer type

int main() {
    char ch = 'a';
    int x;
    x = ch; 
    printf("x=%c", x);
}

Is this code safe to use (considering endiness of machine)?

Upvotes: 1

Views: 422

Answers (5)

chux
chux

Reputation: 153517

Yes, it is safe to cast a character (like char) type to an integer type (like int).

In this answer and others, endian-ness is not a factor.

There are 4 conversions going on here and no casting:

  1. a is character of the C encoding. 'a' converts to an int at compile time.

    'a'
    
  2. The int is converted to a char.

    char ch = 'a';
    
  3. The char ch is converted to an int x. In theory there could be a loss of data going from char to int **, but given the overwhelming implementations, there is none. Typical examples: If char is signed in the range -128 to 127, this maps well into int. If char is unsigned in the range 0 to 255, this also maps well into int.

    int x;
    x = ch; 
    
  4. printf("%c", x) uses the int x value passed to it, converts it to unsigned char and then prints that character. (C11dr §7.21.6.1 8 @haccks) Note there is no conversion of x due to the usual conversion of variadic parameters as x is all ready an int.

    printf("x=%c", x);
    

** char and int could be the same size and char is unsigned with a positive range more than int. This is the one potential problem with casting char to int although typically there is not loss of data. This could be further complicated should char have range like 0 to 2³²-1 and int with a range of -(2³¹-1) to +(2³¹-1). I know of no such machine.

Upvotes: 3

programmerjake
programmerjake

Reputation: 1824

it is safe here because char is converted to int anyway when calling printf.

see C++ variadic arguments

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60067

Yes, casting integer types to bigger integer types is always safe.

Standard library's *getc (fgetc, getchar, ...) functions do just that--they read unsigned chars internally and cast them to int because int provides additional room for encoding EOF (end of file, usually EOF==-1).

Upvotes: 1

Nicolas Charvoz
Nicolas Charvoz

Reputation: 1509

What you are doing is first =

int x = ch => Assigning the ascii value of the char to an int

And finally : printf("x=%c", x); => Printing the ascii value as a char, which will print the actual char that correspond to that value. So yeah it's safe to do that, it's a totally predicatable behaviour.
But safe does not mean useful as integer is bigger than char, usually we do the inverse to save some memory.

Upvotes: 0

mantal
mantal

Reputation: 1209

Yes it is, because int is bigger than char, but using char instead of int would not be safe for the same reason.

Upvotes: 0

Related Questions