Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement in c++

Hay Dear!

i know that if statement is an expensive statement in c++. I remember that once my teacher said that if statement is an expensive statement in the sense of computer time.

Now we can do every thing by using if statement in c++ so this is very powerful statement in programming perspective but its expensive in computer time perspective.

i am a beginner and i am studying data structure course after introduction to c++ course. my Question to you is
Is it better for me to use if statement extensivly?

like image 930
Zia ur Rahman Avatar asked Feb 02 '10 09:02

Zia ur Rahman


2 Answers

If statements are compiled into a conditional branch. This means the processor must jump (or not) to another line of code, depending on a condition. In a simple processor, this can cause a pipeline stall, which in layman's terms means the processor has to throw away work it did early, which wastes time on the assembly line. However, modern processors use branch prediction to avoid stalls, so if statements become less costly.

In summary, yes they can be expensive. No, you generally shouldn't worry about it. But Mykola brings up a separate (though equally valid) point. Polymorphic code is often preferable (for maintainability) to if or case statements

like image 105
Matthew Flaschen Avatar answered Oct 21 '22 08:10

Matthew Flaschen


I'm not sure how you can generalise that the if statement is expensive.

If you have

if ( true ) { ... }

then this the if will most likele be optimised away by your compiler.

If, on the other hand, you have..

if ( veryConvolutedMethodTogGetAnswer() ) { .. }

and the method veryConvolutedMethodTogGetAnswer() does lots of work then, you could argue tha this is an expensive if statement but not because of the if, but because of the work you're doing in the decision making process.

"if"'s themselves are not usually "expensive" in terms of clock cycles.

like image 33
ScaryAardvark Avatar answered Oct 21 '22 07:10

ScaryAardvark