tags:

views:

1358

answers:

4

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
+4  A: 

The line with the error looks like you're trying to call GetMonth -- but you can only do that inside of a function:

#ifdef TEST
int main() { 
    GetMonth();
    return 0;
}
#endif
Jerry Coffin
You can call a function outside of a function, if it is an initializer. See AndreyT's answer: http://stackoverflow.com/questions/1573168/error-expected-constructor-destructor-or-type-conversion-before-token/1573344#1573344
Richard Corden
+3  A: 

In C/C++, you cannot simply add executable code into the body of a header or implementation (.c,.cpp,.cxx,etc...) file. Instead you must add it to a function. If you want to have the code run on startup, make sure to add it to the main method.

int main(int argc, char *argv[]) {
  GetMonth();
}
JaredPar
+2  A: 

C++ programs don't execute in a global context. This means you need to put the call to GetMonth into a function for it to run. int main() { } might be appropriate.

Andres Jaan Tack
+2  A: 

(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.

AndreyT
+1 for mentioning global initializer.
Richard Corden