if statement condition.

I've noticed that in many programming languages including C++, whenever you put a function as a condition for the if statement, it calls that function.

1
2
3
4
5
6
7
8
bool doSomething(){
    cout << "Hello" << endl;
}

int main(){
    if(doSomething()){
        cout << "World!" << endl;
}


this code will print "Hello" to the screen. If you put return true inside the doSomething function, it will print "World!". Does anyone know why this works?
Last edited on
Because the compiler spliced in a "return false" at the end of doSomething since you didn't specify a return value yourself.

-Albatross
No, that's not what i'm saying. It was just a thing that I was wondering. (why does if statement calls whatever inside the bracket ex. why does if statement calls doSomething?). But anyway thanks.
Last edited on
That is exactly what you are saying. And @Albatross answered your question perfectly.
Last edited on
You are wondering, why we are not limited to writing either if ( true ) or if ( false ). That would be rather limiting, wouldn't it?

What language syntax has is:
[output]IF ( expression )[/code]
The expression is evaluated during runtime and the result of evaluation is either true or false. That makes sense, doesn't it?

Now, lets take a simple example:
if ( a < b )
That isn't a function call.




... or is it?

Lets reveal a bit more:
1
2
3
4
5
6
bool operator< ( const Foo &, const Foo & ); // function declaration

// code
Foo a = ...;
Foo b = ...;
if ( a < b )

What did look like an innocent "is a less than b" expression, is suddenly a function. Just to be sure, lets write that last line again, but avoiding the operator syntax:
if ( operator< ( a, b ) )
The condition expression contains a function call. The expression can be evaluated only by calling the function.

Does that answer your question?


Then the lazy fellow:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using std::cout;

bool foo() {
  cout << "Hello ";
  return false;
}

bool bar() {
  cout << "world ";
  return true;
}

int main() {
  if( foo() && bar() ) {
    cout << "Dolly!\n";
  }
  cout << '\n';
  return 0;
}
can i just take a moment to say thats whats awesome about lisp(s)? you realize everything is a function, such as (+ 3 4)
you realize everything is a function

Isn't that the case for every language?
Or is the awesome thing about lisp that you do realize it?
Isn't that the case for every language?

not neccesarily. for example, in racket:
(+ 3 4)
and in c++:
3 + 4
while the result is exactly the same, operators have a few differences from functions. namely operator precedence. in lisp precedence is very simple, since everything is actually a function. another example is in racket, (while) is a function, and in c++ its a loop. (not sure about (for))
Also, comparison operators for basic types are very different from function calls at a technical level.

-Albatross
Topic archived. No new replies allowed.