-2

I am wondering complexity of following if statement

if (isTrue()) //case 1

VS

if(isTrue()==true) //case 2

And isTrue defined as

boolean isTrue(){
//lots of calculation and return true false based on that.
 return output;
}

I was thinking, complexity of if (isTrue()) is lower then if(isTrue()==true) because on case 2 require additional comparison for equals.

What about space complexity?

Any different thought?

minhaz
  • 4,233
  • 3
  • 33
  • 49
  • 1
    How is there an additional comparison? – Dave Newton Mar 16 '13 at 19:20
  • because compiler have to check function output with its right side value and then to test with if condition – minhaz Mar 16 '13 at 19:24
  • 1
    @minhaz Most compilers would probably just optimize out those `if`s entirely, since `isTrue` will only ever return `true`. – Jeffrey Mar 16 '13 at 19:28
  • I guess thats bad example, consider that function has one million lines of code. – minhaz Mar 16 '13 at 19:29
  • 1
    @minhaz There's no difference between `if (foo)` and `if (foo == true)`. `if (foo)` still has to check `foo` for true. – Dave Newton Mar 16 '13 at 19:32
  • 1
    @DaveNewton That's not correct. By the same logic you give, 'if (foo == true)' has to check 'foo == true' for being true. A compiler would be expected to optimise all the excess crud away but it's not the same thing. – user207421 Mar 17 '13 at 00:20

3 Answers3

3

Both of them are same in speed/space. But second way is weird for C/C++ programmers.

The different is, second way is just less readable.

masoud
  • 55,379
  • 16
  • 141
  • 208
2

They are equivalent. And when doing global optimizations condition is removed altogether.

Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18
1

The second case (checking for ==true) can get problematic if you or someone else redefines the value of true.

Let's say that we have the following C code:

#define true 2

bool isEqual(int a, int b)
{
    return (a == b);
}

if (isEqual(5, 5)) {
    printf("isEqual #1\n");
}

if (isEqual(5, 5) == true) {
    printf("isEqual #2\n");
}

The output from this code will be

isEqual #1


So the shorter form where you leave out ==true is preferable not only because it leads to less verbose code but also because you avoid potential problems like these.

Michael
  • 57,169
  • 9
  • 80
  • 125