简体   繁体   中英

Convert char to int in C?

I was reading some examples in how to convert char to int, and i have this code:

#include <stdio.h>

int main()
{
    char ch1 = 125, ch2 = 10;
    ch1 = ch1 + ch2;
    printf("%d\n", ch1);
    printf("%c\n", ch1 - ch2 - 4);
    return 0;
}

as i know that if we made any Character arithmetic the char type will convert to int

so why the result of first printf statement is -121 not 135 as i know int range will handle 135 so no overflow will happened.

the second printf statement will print y because we put %c in the printf.

The "char" variable types usually default to the "signed char" type.
The "signed char" variables have a range of values from -127 to +127.

Exceeding this positive range limit caused the negative result from this program.

As correctly pointed out by bolov, the result is a char type, so you are converting it back to char.

Explanation: Since the result of ch1 + ch2 is stored in ch1 , which is a char type, the calculation operation will max out at 127 and will continue, starting from the lowest char value of -128. So the resulting ch1 will be -121:

ch1 =  -128 - 1 + (125 + 10 - 127)
or ch1 = -121

To resolve this, just store the result to an int variable or if you really want to optimize the memory, then to an unsigned char variable.

#include <stdio.h>
int main(){
    char ch1 = 125, ch2 = 10;
    unsigned char ch3;
    ch3 = ch1 + ch2;
    ch1 = ch1 + ch2;
    printf("%d\n", ch1);
    printf("%c\n", ch1 - ch2 - 4);
    printf("%d\n", ch3);
    return 0;
}

Result:

-121
y
135

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM