smartnerd
smartnerd

Reputation: 85

How is a multi-char variable of type char (and not char array) is processed in C?

I tried this

#include<stdio.h>



int main(void){

char charVal1 = '1';
char charVal2 = '91';

printf("%d\n", charVal1);
printf("%d", charVal2);
}

The output of the first printf statement is 49. But the other one is showing 14641. How 91 is converted into 14641? Also, sometimes it shows that the implicit conversion resulted in overflow and the output is 49.

Upvotes: 0

Views: 35

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20812

In your system, the character '1' is encoded as 49. C requires that the characters '1'…'9' be in that order and contiguous so on your system '9' is encoded as 57. So, '91' is encoded as 57 followed by 49. In hexadecimal, this 0x39 followed by 0x31. If you consider that two-byte integer (possibly a short [aka short int] on your system) with the big-endian byte ordering, it is 0x3931 or 14641. So your machine uses the big-endian byte ordering.

'91' is an int with a value 14641. On my system, int is bigger than char and char is -128 to 128 so assigning a char with an integer outside that range, gives a compiler warning.

Now your formatted print call uses the "%d" format specifier, which is for normal length integers. This means that it will convert however many bytes an integer is on your system to decimal and output that. But, you are passing it char values so it is printing those values as integers, or 91 and 14641.


You probably mean something more like this:

char[] strVal1 = "1";
char[] strVal2 = "91";

printf("%s\n", strVal1);
printf("%s", strVal2);

Upvotes: 1

Related Questions