C language - implicit type conversion and arithmetic conversion

The order of expression evaluation is generally determined according to the priority order of operators. However, the process of evaluating some expressions also involves type conversion and unification.

Table of contents

implicit type conversion

Integer promotion

When does integer promotion occur?

Arithmetic conversion


implicit type conversion

There are always expression calculations of short, char type and int type in C language during evaluation and calculation. At this time, we should perform integer promotion to promote types below int to an integer before calculation.

So how to upgrade the plastic surgery?


Integer promotion

Integer promotion is to promote the two's complement of the number according to the sign bit of the variable's data type.

Supplement: How an integer is promoted is also related to the data type. The above is only for signed integers. For the promotion of unsigned integers, we adopt the method of directly filling the high bits with 0.


Example:

 Why is the calculation result here like this? Isn't it 128? Please read on:


So let’s take a look at this little question: Guess the print result


When does integer promotion occur?

I believe that after studying the above content, you have a certain understanding of plastic surgery. To impress you, please see:

 Isn’t this much better? Just use it directly.


Arithmetic conversion

The object of arithmetic conversion is the conversion between types above int. That is to say, when any two of the following types are calculated, the types will be unified and unified into a higher type (that is, the upward conversion in the figure)


A little question:

#include <stdio.h>
int i;        //全局变量未给初始值时,自动默认为0
int main()
{
    i--;
    if (i > sizeof(i))
    {
        printf(">\n");
    }
    else
    {
        printf("<\n");
    }
    return 0; 
}

This question is very hidden, and the blogger also fell into it. Now I share it with you:

The variable i is a number of type int, and sizeof(i) is of type unsigned int to be precise. From the above chart, you will find that unsigned int is above int, so the compiler secretly performs arithmetic conversion when executing this line. , uniformly converted into unsigned int type, so -1 on the left side of the formula is converted into unsigned int and becomes a huge word, which is far larger than the value of sizeof(i).

Guess you like

Origin blog.csdn.net/C_Rio/article/details/128954085