Is relational comparison between int and float directly possible in C?

后端 未结 11 2113
Happy的楠姐
Happy的楠姐 2020-12-03 18:48

I am using Visual Studio 6 with some old time code written in c. I found an issue where the code looks like this..

int x = 3;
float y = 3.0;

if(x == y){
            


        
11条回答
  •  一个人的身影
    2020-12-03 19:20

    I am going to buck the trend here a bit. As to the first question about whether the comparison is valid, the answer is yes. It is perfectly valid. If you want to know if a floating point value is exactly equal to 3, then the comparison to an integer is fine. The integer is implicitly converted to a floating point value for the comparison. In fact, the following code (at least with the compiler I used) produced identical assembly instructions.

    if ( 3 == f )
        printf( "equal\n" );
    

    and

    if ( 3.0 == f )
        printf( "equal\n" );
    

    So it depends on the logic and what the intended goal is. There is nothing inherently wrong with the syntax.

提交回复
热议问题