sriram
sriram

Reputation: 9032

How does C executes its IF statement?

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?

Upvotes: 2

Views: 288

Answers (3)

Lindydancer
Lindydancer

Reputation: 26094

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.

Upvotes: 7

Pascal MARTIN
Pascal MARTIN

Reputation: 400972

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.

Upvotes: 4

Bwmat
Bwmat

Reputation: 4578

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

Upvotes: 1

Related Questions