Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: expected constructor, destructor, or type conversion before ';' token?

I'm trying to compile my code to test a function to read and print a data file, but I get a compiling error that I don't understand - "error: expected constructor, destructor, or type conversion before ';' token". Wall of relevant code-text is below.

struct Day
{
  int DayNum;
  int TempMax;
  int TempMin;
  double Precip;
  int TempRange;
};

struct Month
{
  Day Days[31];
  int MonthMaxTemp;
  int MonthMinTemp;
  double TotalPrecip;
  int MonthMaxTempRange;
  int MonthMinTempRange;
  double AverageMaxTemp;
  double AverageMinTemp;
  int RainyDays;
  double AveragePrecip;
}theMonth;

double GetMonth();

double GetMonth()
{
  for (int Today = 1; Today < 31; Today++)
    {
      cout << theMonth.Days[Today].TempMax << theMonth.Days[Today].TempMin;
      cout << theMonth.Days[Today].Precip;
    }
  return 0;
}

GetMonth();  // compile error reported here
like image 910
Owen Pierce Avatar asked Oct 15 '09 15:10

Owen Pierce


2 Answers

The line with the error looks like you're trying to call GetMonth -- but at the global level, a C++ program consists of a series of declarations. Since a function call isn't a declaration, it can't exist in isolation at the global level. You can have a declaration that's also a definition, in which case it can invoke a function as part of initialization.

A function call by itself, however, has to be contained within some other function:

#ifdef TEST
int main() { 
    GetMonth();
}
#endif
like image 199
Jerry Coffin Avatar answered Sep 22 '22 17:09

Jerry Coffin


(In addition to other replies.) In order to excute your 'GetMonth()' function you have to either call it from another function ('main' or whatever is called from 'main') or use it in initializer expression of an object declared at namespace scope, as in

double global_dummy = GetMonth();

However, the latter method might suffer from initialization order problems, which is why it is recommended to use the former method whenever possible.

like image 32
AnT Avatar answered Sep 20 '22 17:09

AnT