C++ identifier is undefined

Reducing to three lines (the other errors are analogous):

int wall;    
getGallons(wall);
getHours(gallons); // error here

While wall is defined, gallons is not. And where do you want to get gallons from anyway? The result is hidden deep inside another function. How do you want to get it out from there?

Well, you need a return value:

  int getGallons(int wall)
//^^^ !
{
     int gallons = wall / 112;
     // ...
     return gallons; // !
}

This way, you can use your function like this:

int gallons = getGallons(wall);
// now gallons is defined and you can use it:
getHours(gallons);

Analogously for the other functions and variables.

Usually, it is not a good idea to mix logic (calculations) and output in the same fucntion. So I’d rather move writing to console into main function:

int getGallons(int wall) { return wall / 112; }
int getHours(int gallons) { return gallons * 8; }

int wall;
std::cin >> wall;
int gallons = getGallons(int wall);
std::cout << ...;
int hours = getHours(gallons);
std::cout << ...;

Notice? All input/output now is at the same level…

Side note: It is not necessary to declare functions before defining them if you don’t use them before definition:

//void f(); // CAN be ommitted
void f() { };
void g() { f(); }

Counter-example:

void f();
void g() { f(); } // now using f before it is defined, thus you NEED do declare it
void f() { };

If you still want to keep the declarations is rather a matter of style (but will get important when managing code in different compilation units, as you’d then have the declarations in header files – you’ll encounter soon in next lessons).

Leave a Comment