Home > OS >  (long) i (int) j * k What is the type of the expression?
(long) i (int) j * k What is the type of the expression?

Time:02-10

int i;
long j;
unsigned int k;

I'm new to learning C, and can't figure this out. I've tried looking online many times for similar expressions. I honestly don't need the answer I really just want to understand how to figure it out. This has to do with mixing data types and I've only come across little information about what they are, but nothing clear to understand. Any help would be appreciated to understand how to figure out the data type for the following expression (long) i (int) j * k

I appreciate any answers! Thank you!

CodePudding user response:

We have long int * unsigned.

The * expression will be unsigned. The reason is that int and unsigned have the same conversion rank, and the unsigned type wins: the signed operand is converted to unsigned, and the multiplication is between two unsigned, its result being of that type.

Thus, the addition is then long unsigned. Here things get tricky. If the implementation's long can represent all of the values of unsigned, then the unsigned will be converted to long; the addition is of two long operands and the result is long. But if unsigned has values outside of the long range (e.g. 32 bit unsigned and 32 bit long), then both operands will convert to unsigned long and the addition will be in that type.

In other words, the type ends up being platform-specific, depending on the relative range of unsigned and long.

CodePudding user response:

Check out Implicit type promotion rules. Then use that together with operator precedence to figure out how which operands that bind to each other - type promotion will be per sub expression, then the resulting type of each sub expression becomes the operand for the next.

Multiplication naturally has higher precedence than addition and casts have higher precedence still, so the expression is equivalent to this:

((long)i) ( ((int)j) * k )

In the subexpression inside the parenthesis, there's an explicit conversion of j to int, then the usual arithmetic conversions as per the above link determines the type used for that subexpression. It also becomes the resulting type used when determining what type to use for the addition. Once again, it's the usual arithmetic conversions.

  • Related