Search code examples
c++functionprogram-entry-pointdeclare

c++ ‘total’ was not declared in this scope. MAIN


#include <iostream>
using namespace std;

int population(int current_pop)
{
   int Time;
   int birth;
   int immigrant;
   int death;
   int total;
   Time = 24*60*60*365; // convet day to second
   birth = Time/8;
   death = Time/12;
   immigrant = Time/33; // calculate the rate of the death, birth,immigrant
   total = birth+immigrant-death+current_pop; // make sum
   return total;
}

int main() {
   int current_pop = 1000000;
   population(current_pop); //test
   cout << total << endl;
}

it just show that error: ‘total’ was not declared in this scope cout << total << endl;

Why? And If i already declared a value should i declare it again in the main function?


Solution

  • Like the error said, you declared total variable inside population() which will not be available in main() function. population() function will have its own scope so that any variables declared inside it, only accessible there.
    To make it available then you need to declare it inside main().

    int main() {
        ...
        int total = population(current_pop);
        ...
    }