2

I was coding some problem when i observed this. Since Functions are supposed to be a group of statements that is given a name, which can be called from some point of the program. Consider a simple program that gives the absolute value of an integer :

#include <iostream>
#include <vector>
using namespace std;

int getAbsolute(int x) {
  return x > 0 ? x : -1*x;
}

int main() {
  vector<int> arr;

  for(int i = -5; i < 5; i++) 
    arr.push_back(i);

  for(int i = 0; i < arr.size(); i++) {
    cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;
  }
}

When i run this program :

rohan@~/Dropbox/cprog/demos : $ g++ testFunction.cpp 
rohan@~/Dropbox/cprog/demos : $ ./a.out
abs(-5) : 1
abs(-4) : 1
abs(-3) : 1
abs(-2) : 1
abs(-1) : 1
abs(0) : 1
abs(1) : 1
abs(2) : 1
abs(3) : 1
abs(4) : 1
rohan@~/Dropbox/cprog/demos : $ 

My question is, Why doesn't this program give me error that i'm supposed to call with arguments, Is something wrong with my g++(-v 4.8.5)? And why does this program output's 1 on each call? Or am i missing something here? I'm really confused.

Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40

1 Answers1

1

This statement

cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;

is correct. The function designator getAbsolute implicitly is converted to the function pointer int (*)( int ) according to the function declaration

int getAbsolute(int x);

and this pointer is outputted using the following operator operator <<

basic_ostream<charT,traits>& operator<<(bool n); 

and you get the result like this

abs(-5) : 1

because the function pointer is unequal to zero and this operator is the best overloaded operator operator << for a function pointer of such type.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335