What are the general rules for comparing different data types in C?

后端 未结 4 1734
情歌与酒
情歌与酒 2020-12-10 14:32

Lets say I have the following scenarios:

int i = 10;
short s = 5;

if (s == i){
   do stuff...
} else if (s < i) {
  do stuff...
}

When

4条回答
  •  心在旅途
    2020-12-10 15:12

    Datatypes are an abstraction of sorts .. as far as computer is concerned there are no int or short. There is memory and there is data.

    When you say int x, you are saying to a computer "give me enough bytes to store an int", when you say short y, you are saying ... you guessed it.

    short, as you would expect takes less bytes then an int and therefore may (and often does) contain data in the adjacent bytes. When comparing data of different types the issue is "will adjacent bits cause skewed results or not?"

    Whenever you compare two different datatypes you really are comparing bits stored in two different locations. Max number of individual bits stored to represent the data need to be the same size for a comparison to work

    Casting is used to help with this.

提交回复
热议问题