Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous result with char and toupper

How does 'ab' was converted to 24930 when stored in char?

#include<stdio.h>

int main(){
    char c = 'ab';
    c = toupper(c);
    printf("%c", c);
    return 0;
}

GCC compiler warning : Overflow in conversion from 'int' to 'char' changes value from '24930' to '98'

Output : B

If possible please explain how char handled the multiple characters here.

like image 903
Naman Jain Avatar asked Jan 28 '26 07:01

Naman Jain


1 Answers

From the C Standard (6.4.4.4 Character constants)

10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

So this character constant 'ab' is stored as an object of the type int. Then it is assigned to ab object of the type char like in this declaration

char c = 'ab';

then the least significant byte of the object of the type int is used to initialize the object c. It seems in your case the character 'b' was stored in this least significant byte and was assigned to the object c.

like image 168
Vlad from Moscow Avatar answered Jan 29 '26 22:01

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!