1) printf(...">

Promotion of data in c

In the following code:

#include "stdio.h" signed char a= 0x80; unsigned char b= 0x01; void main (void) { if(b*a>1) printf("promoted\n"); else if (b*a<1) printf("why doesnt promotion work?"); while(1); } 

I expected to be "promoted" for print. But this is not so. Why? If I can use data types for signed and unsigned ints and have a negative number, for example 0x80000000 and b as a positive number, 0x01, the β€œpromoted” will be printed as expected.

PLZ HELP me understand what the problem is!

+6
source share
2 answers

You have just been caught dirty type C promotion rules.

In C, intermediate elements of an integral type smaller than int are automatically raised to int .

So you have:

 0x80 * 0x01 = -128 * 1 

0x80 gets an extended int type subscription:

 0xffffff80 * 0x00000001 = -128 * 1 = -128 

So the result is -128 and therefore less than 1 .


When using the int and unsigned int types, both operands get to unsigned int . 0x80000000 * 0x01 = 0x80000000 as an unsigned integer greater than 1 .


So, here is a comparison of the type promotion that takes place:

 (signed char) * (unsigned char) -> int (signed int ) * (unsigned int ) -> unsigned int (signed char)0x80 * (unsigned char)0x01 -> (int) 0xffffff80 (signed int )0x80000000 * (unsigned int )0x01 -> (unsigned int)0x80000000 (int) 0xffffff80 is negative -> prints "why doesnt promotion work?" (unsigned int)0x80000000 is positive -> prints "promoted" 

Here is a link to type C promotion rules.

+10
source

Reason printf("promoted\n"); never starts because b*a always == -128 , which is less than 1

 ab 0x80 * 0x01 = -128 * 1 
+2
source

Source: https://habr.com/ru/post/909919/


All Articles