1

I have just switched from Java to C++, so can someone explain what is wrong with this piece of code:

#include "x.hpp"
#include <iostream>
using namespace std;

int min(int a,int b,int c){
 return minimum(minimum(a,b),c);
}

int minimum(int a,int b){
  if(a<b) return a;
  return b;
}

int main()
{
  cout<<min(1,2,3)<<"\n";
  return 0;
}

Compiler says that minimum is undeclared. But why?

P.S. my IDE is Xcode

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
Andre Liberty
  • 707
  • 1
  • 9
  • 17

2 Answers2

3

minimum needs to have been declared at the point of the call.

You can move the definition of minimum above min:

int minimum(int a,int b){
  if(a<b) return a;
  return b;
}

int min(int a,int b,int c){
  return minimum(minimum(a,b),c);
}

Or you can forward-declare minimum:

int minimum(int a,int b);

int min(int a,int b,int c){
  return minimum(minimum(a,b),c);
}

int minimum(int a,int b){
  if(a<b) return a;
  return b;
}
Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
1

You're using minimum before you have declared it.

To declare it before its use in min, you could add this before min:

int minimum(int a, int b);

This is a declaration.

You could also move the whole definition of minimum before min.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157