开发者

How does C executes its IF statement?

开发者 https://www.devze.com 2023-02-23 09:29 出处:网络
There is no boolean type in C programming language, but then how does the C开发者_StackOverflow language turn\'s IF/Else to true and false?

There is no boolean type in C programming language, but then how does the C开发者_StackOverflow language turn's IF/Else to true and false?

What is happening behind the scenes?


The compiler does not convert the conditional expression to a boolean value before it decides which branch of the if/else statement should be taken. Instead it generates assembler instructions just like you would have written if you would have written the program in assembler.

A simple example:

if (x > y)
{
   // Do something
}
else
{
   // Do something else
}

Could be translated into (using a fictitious microcontroller):

    CMP R12,R13
    BLE label1
    // Do something
    JMP label2
label1:
    // Do something else
label2:

If the condition is even simpler, as in:

if (x)

The C language will consider x to be true if it is non-zero and false otherwise.

If the condition contains || and/or && operators, the compiler will generate code that short-circuits the test. In other words, for the expression x != 0 && a/x == y, the second test will not even be performed if the first test is not true. In this case, this is utilized to ensure that a division by zero is not performed.


There is no true and false for a CPU : only 0 and 1.

Basically, in C :

  • Something that is false is equal to 0 -- which a CPU can test
  • And something that is true is not equal to 0 -- which is also something a CPU can test.


for conditionals, a nonzero value is equivalent to true, and a zero value is equivalent to false.

0

精彩评论

暂无评论...
验证码 换一张
取 消