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
asked Oct 15, 2009 at 15:36
1
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
answered Oct 15, 2009 at 15:41
Jerry CoffinJerry Coffin
473k80 gold badges622 silver badges1108 bronze badges
1
(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.
answered Oct 15, 2009 at 16:03
0
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();
}
answered Oct 15, 2009 at 15:41
JaredParJaredPar
729k148 gold badges1236 silver badges1452 bronze badges
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.
answered Oct 15, 2009 at 15:43
Andres Jaan TackAndres Jaan Tack
22.5k11 gold badges59 silver badges77 bronze badges
This guide will help you understand and solve the «Error expected constructor destructor or type conversion before token» error in programming. We will cover the possible reasons for this error and provide step-by-step solutions to fix it. By the end of this guide, you’ll be able to identify the cause of this error and apply the appropriate solution to resolve it.
Table of Contents
- Introduction to the Error
- Common Causes of the Error
- Step-by-Step Solutions
- Mismatched Brackets or Parentheses
- Missing Semicolon
- Incorrectly Declared Class or Function
- FAQ
Introduction to the Error
The «Error expected constructor destructor or type conversion before token» error occurs when the compiler encounters an unexpected token in the source code. This error is common in C++ programming and is generally related to syntax issues. The error message points to the line of code where the unexpected token appears, making it easier for you to identify the cause and fix the error.
Common Causes of the Error
There are several reasons why you might encounter this error in your code. Some of the most common causes include:
- Mismatched brackets or parentheses
- Missing semicolon
- Incorrectly declared class or function
We will discuss each of these causes in detail and provide solutions to fix the error.
Step-by-Step Solutions
Mismatched Brackets or Parentheses
One of the most common causes of this error is mismatched brackets or parentheses. To fix this error, you should carefully review your code and ensure that all opening brackets and parentheses have corresponding closing brackets and parentheses.
int main() {
int a = 5;
if (a > 3) {
cout << "a is greater than 3";
} // This closing bracket was missing
}
Missing Semicolon
Another common cause of this error is a missing semicolon at the end of a statement. Make sure you have placed semicolons at the end of each statement in your code.
int main() {
int a = 5
int b = 6; // There should be a semicolon at the end of this line
cout << a + b;
}
Incorrectly Declared Class or Function
If you have incorrectly declared a class or function, you may encounter this error. Ensure that you have used the correct syntax for declaring classes and functions in your code.
class MyClass {
public: // The colon was missing here
int myFunction() {
return 42;
}
};
FAQ
1. What programming languages are affected by this error?
This error is most commonly encountered in C++ programming. However, similar syntax-related errors can also occur in other programming languages.
2. How can I prevent this error from occurring in the future?
To avoid this error, make sure you follow proper syntax rules when writing your code. Using an Integrated Development Environment (IDE) with syntax highlighting and auto-completion features can also help you identify and fix syntax issues before they lead to errors.
3. Can this error affect the overall performance of my code?
This error will prevent your code from compiling successfully, so it will not directly impact the performance of your code. However, it is essential to fix this error to ensure that your code runs as expected.
4. Why is the error message pointing to the wrong line of code?
The error message points to the line of code where the unexpected token appears. However, the actual cause of the error might be located elsewhere in your code (e.g., a missing bracket or semicolon). Review your code carefully to identify and fix the issue.
5. Can I ignore this error?
No, you cannot ignore this error. It prevents your code from compiling successfully, and you must fix the issue to ensure that your code runs as expected.
- C++ Language Reference
- C++ Programming: Tips on Writing Clean Code
- Best IDEs for C++ Development
Back to Top
Loading
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
#include <iostream> #include <cstdlib> #include <string.h> #include <stdio.h> #include <iomanip> #include <conio.h> #define N 3 using std::cin; using std::cout; using std::endl; class prisList { char *naimenovanie; char tipTovara; float cena; int min; public: void set (char *m, char j, float k, int c); void get (char *m, char &j, float &k, int &c); void show (void); }; void prisList::set (char *m, char j, float k, int c) { strcpy(naimenovanie,m); tipTovara=j; cena=k; min=c; } void prisList::get (char *m , char &j, float &k, int &c) { delete[] m; m=new char [strlen(naimenovanie)+1]; strcpy(m,naimenovanie); j=tipTovara; k=cena; c=min; } void prisList::show(void) { cout<<naimenovanie<<" "; cout<<tipTovara<<" "; cout<<cena<<" "; cout<<min<<" "; } int main() { char *a; char b; float f; float d; short p; } prisList obj[N]; clrscr(); std::cout<<"F-ya SET n"<<endl; for (p=0; p < N; p++) { cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; cin>>a; cin>>b; cin>>f; cin>>d; obj[p].set(a,b,f,d); } cout<<"f-ya SHOW"<<endl; cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; for (p=0; p < N; p++) { obj[p].show(); cout<<"n"; } cout<<"f-ii GET i SHOW"<<endl; cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; for (p=0; p < N; p++) { obj[p].set(a,b,f,d); obj[p].show(); cout<<"n"; } system("PAUSE"); delete[] a; return 0; } |
Offline
Зарегистрирован: 05.12.2015
Здравствуйте, у меня вот такой скетч:
long duration,cm; void setup() { pinMode (10,OUTPUT);//на реле pinMode (11, OUTPUT);// триг pinMode (12, INPUT); //эхо Serial.begin (9600); } void loop() { duration = pulseIn (12,HIGH); cm = duration/29/2; if (cm<20){ digitalWrite(10, HIGH); } //если менее 10см - выключаем else if (cm<=150) // Если расстояние менее 150 сантиметров { digitalWrite(10, LOW); // Включаем светодиод delay(500000); //задержка на выключение } else { digitalWrite(10, HIGH); // иначе выключаем } } else { digitalWrite(10, HIGH); // включаем LOW } Serial.print(cm); Serial.print("CM"); Serial.println (); delay(100); // делает замер каждые -- сек }
При компиляции скетча вылетет такая ошибка:
Arduino: 1.6.0 (Windows 8), Плата»Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)»
HC-SR04.ino:44:1: error: stray » in program
HC-SR04.ino:34:1: error: expected unqualified-id before ‘else’
HC-SR04.ino:38:1: error: ‘Serial’ does not name a type
HC-SR04.ino:39:1: error: ‘Serial’ does not name a type
HC-SR04.ino:40:1: error: ‘Serial’ does not name a type
HC-SR04.ino:42:6: error: expected constructor, destructor, or type conversion before ‘(‘ token
HC-SR04.ino:44:1: error: expected declaration before ‘}’ token
Ошибка компиляции.
This report would have more information with
«Отображать вывод во время компиляции»
enabled in File > Preferences.
Подскажите пожалуйста что здесь не так. В програмировании я новичёк:)
Не судите строго.