Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C executes its IF statement?

Tags:

c

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

What is happening behind the scenes?

like image 238
sriram Avatar asked May 02 '26 16:05

sriram


1 Answers

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.

like image 150
Lindydancer Avatar answered May 05 '26 09:05

Lindydancer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!