Tai
Tai

Reputation: 446

What's the point of if(true)? c++

I've seen if(true) used a bunch of times.

int a = 10;
if(true){
    int b = 20;
}
int c = 15;

I don't understand what the point of putting if(true) there. Does it always evaluate to true, meaning it always executes? It's not part of a function. It's just there. Does it have to do with memory allocation?

Upvotes: 3

Views: 10987

Answers (2)

user1084944
user1084944

Reputation:

If one is fiddling with the code, it's very easy to turn

if (true) {
    // block of code
}

into

if (false) {
    // block of code
}

so this is a useful construct if you often need to turn a block of code on/off. It could also be a placeholder for future changes, where the boolean value is replaced with a (template) parameter or global constant or somesuch. (or a holdover from a former change that did the reverse)

Upvotes: 3

marcinj
marcinj

Reputation: 49976

This is equivalent to :

{
    int b = 20;
}

maybe someone was using if (false) then switched to if (true). if(false) makes actually sense because you are removing some code - it should not get into compiled exe, but it gets compiled by compiler - and checked for any errors.

Upvotes: 2

Related Questions