After I reformatted your code so it would display tolerably on the website, the errors stand out pretty clearly.
I would recommend, when you use brackets around the if
clause, also use them around the else
clause:
if (foo) {
/* ... */
} else {
/* ... */
}
Leaving off the brackets is quite fine if both cases are just one statement. And while there’s no requirement about putting brackets around both clauses if only one needs them, I have found plenty of bugs around if
statements with brackets around only one path. It’s surprising.
On a further note, a text editor with bracket-matching capabilities would be a huge assistance. Many editors will highlight brackets that aren’t properly nested, and some provide a key to jump between them quickly. (In vi
and clones, the %
key will bounce between ()
, {}
, []
and <>
pairs. Very handy.)
This comprehensive guide will walk you through the process of resolving the «Expected declaration before ‘}’ token» error in your code. This error is commonly encountered when working with C, C++, or JavaScript languages, and occurs when the compiler encounters an unexpected closing brace that does not correspond to an opening brace within the same scope.
Table of Contents
- Understanding the Error
- Identifying the Cause
- Step-by-Step Solutions
- FAQs
Understanding the Error
The «Expected declaration before ‘}’ token» error occurs when there is a mismatch between the opening and closing braces in your code. This could be due to a missing opening brace, an extra closing brace, or a misplaced closing brace. In some cases, it might also be caused by incorrect nesting of braces.
To fix this error, you need to identify the cause and ensure that all opening and closing braces are correctly paired and nested.
Identifying the Cause
Missing Opening Brace: If you forget to include an opening brace for a code block, the compiler will treat the closing brace as unexpected and throw an error.
int main() {
// Code here...
// Missing opening brace
}
Extra Closing Brace: If you accidentally include an extra closing brace in your code, the compiler will not be able to find a matching opening brace and will throw an error.
int main() {
// Code here...
}
} // Extra closing brace
Misplaced Closing Brace: If a closing brace is placed in the wrong position, the compiler will not be able to match it with the corresponding opening brace and will throw an error.
```c
int main() {
// Code here...
} // Misplaced closing brace
}
```
Step-by-Step Solutions
Follow these steps to resolve the «Expected declaration before ‘}’ token» error in your code:
Carefully review your code, paying close attention to the opening and closing braces. Look for any missing, extra, or misplaced braces.
Ensure that all opening braces have a corresponding closing brace, and that they are correctly nested. Use proper indentation to make this task easier.
If you find a missing opening brace, add it in the appropriate position.
If you find an extra closing brace, remove it.
If you find a misplaced closing brace, move it to the correct position.
Once you have made the necessary changes, recompile your code and ensure that the error has been resolved.
FAQs
1. How do I find the line number where the error occurred?
Most compilers will display the line number where the error was detected in the error message. You can use this information to quickly locate the problematic section of your code.
2. How can I prevent this error from happening in the future?
To prevent this error, always make sure to properly pair and nest your opening and closing braces. Additionally, using a good IDE or text editor with syntax highlighting and automatic indentation can help you quickly identify any brace-related issues.
3. How do I fix this error in an IDE like Visual Studio or Eclipse?
IDEs like Visual Studio or Eclipse typically provide error detection and code analysis tools that can help you identify and fix brace-related issues. These tools may automatically highlight problematic lines, or provide suggestions for resolving the issue.
4. Can this error occur in languages other than C, C++, or JavaScript?
Yes, this error can occur in any programming language that uses braces to define code blocks, such as Java or Swift. The steps to resolve the error are similar across all languages.
5. Is there a difference between braces, curly brackets, and curly braces?
No, these terms all refer to the same punctuation marks: {
and }
. They are used interchangeably to describe the opening and closing braces used in programming languages to define code blocks.
Debug C++ in Visual Studio Code
How to debug C++ programs in Visual Studio Code.
MicrosoftMicrosoft
Lex0R 0 / 0 / 0 Регистрация: 28.03.2013 Сообщений: 5 |
||||
1 |
||||
10.06.2013, 19:08. Показов 25136. Ответов 4 Метки нет (Все метки)
Добрый день, пытаюсь освоить списки, пока почти ничего ещё не понял. Вообщем собираюсь сделать несколько элементов списка, так же поиск и удаление элементов, до удаления ещё не дошёл.
0 |
Croessmah Неэпический 17815 / 10586 / 2044 Регистрация: 27.09.2012 Сообщений: 26,631 Записей в блоге: 1 |
||||
10.06.2013, 19:20 |
2 |
|||
1 |
Lex0R 0 / 0 / 0 Регистрация: 28.03.2013 Сообщений: 5 |
||||
10.06.2013, 19:23 [ТС] |
3 |
|||
Тьфу ты блин, я уже минут 20 сижу эти скобки считаю, проглядел. Ещё вопрос можно?
0 |
Неэпический 17815 / 10586 / 2044 Регистрация: 27.09.2012 Сообщений: 26,631 Записей в блоге: 1 |
|
10.06.2013, 19:29 |
4 |
Можете почитать книгу Уильям Топп, Уильям Форд «Структуры данных в C++»
1 |
0 / 0 / 0 Регистрация: 28.03.2013 Сообщений: 5 |
|
10.06.2013, 19:38 [ТС] |
5 |
Можете почитать книгу Уильям Топп, Уильям Форд «Структуры данных в C++» Благодарю за помощь.
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.
Подскажите пожалуйста что здесь не так. В програмировании я новичёк:)
Не судите строго.
Below is my code. The idea is it is supposed to wait for the ? character, print K, and turn on the LED. If it does not detect ? then it should keep waiting.
Below is my code:
incomingByte = Serial.read();
sendBack = K;
int pollTime = 200;
int ledPin = 9;
bool running = true;
void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {
while(Serial.available()) {
if(Serial.read == '?') {
Serial.print(sendBack);
pinMode(9,OUTPUT);
else {
delayMicroseconds(pollTime);
}
}
}
}
asked Oct 16, 2016 at 23:43
1
Try this:
void setup() {
Serial.begin(9600); //set baud rate.
pinMode(9, OUTPUT);
}
void loop() {
if (Serial.available()) { //Gets you the number of bytes that are available to be read from the serial port.
if (Serial.read() == '?') {
Serial.println("OK");
digitalWrite(9, HIGH);
delay(1000);
}
}
else
{
digitalWrite(9, LOW);
}
}
answered Oct 17, 2016 at 0:21
Dat HaDat Ha
2,9036 gold badges21 silver badges44 bronze badges