[SOLVED] Calling boolean function without an argument inside of an if-statement in C++

Issue

I was wondering, why is there no error when the block of code below is executed? The error should come from the func1 block, because we are calling func2 without an argument. What is being passed in the argument to func2?

I also realized this only happens when func2 is a boolean function, and if it is called inside an if statement. I know that "-4" is not passed from the main function, because the output is "1" when it should be "0".

#include <iostream>

bool func2(int b) {
  return b>0;
}

int func1(int a) {
  if (func2) return 1;
  else return 0;
}

int main() {
  std::cout << func1(-4);
  return 0;
}

Solution

The reason the code doesn’t fail to compile is because of function-to-function-pointer decay.

When you use just the name of a function, it will decay into a pointer to that function. The pointer can then be converted to a bool that will be true if the pointer points to something, and false if it is a null pointer.

Since the pointer is pointing to a function, it will have a non-null value, and that means the expression will evaluate to true.

Answered By – NathanOliver

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *