Ошибка expected declaration before token

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

  1. Understanding the Error
  2. Identifying the Cause
  3. Step-by-Step Solutions
  4. 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

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день, пытаюсь освоить списки, пока почти ничего ещё не понял. Вообщем собираюсь сделать несколько элементов списка, так же поиск и удаление элементов, до удаления ещё не дошёл.
В данный момент программа ругается на поиск в списке, точнее на последнюю строку, она же «}», подскажите что не так?

C
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
91
92
93
94
95
96
97
98
99
100
#include <iostream.h>
#include <conio.h>
 
using namespace std;
 
struct list
{ 
   int id;    
   int first;
   int second;
   list *next;
}; 
 
int main ()
{   
   
   char a; 
   int i;
   int n;                               // Êîë-âî ñïèñêîâ
   list *phead, *t;
 
   phead = new (list);
   t = phead;
////////////////////////////////////////   
 
   while (i!=5) 
   {                                     //Ïðîâåðêà íà êîë-âî ââîäîâ
   cout<<"Number of list's: ";  
   cin>>n;
   
   if (n<1)
      {
           cout<<"Error, try again!"<<endl;
           getch();
           system("cls"); 
      }
      else
           {break;}
   }
   
   cout<<endl;
////////////////////////////////////////
   
   for (i=1; i<n; i++)                  //Ââîäèì ýëåìåíòû
   {
       (*t).id=i;
       cout<<"Enter First: ";
       cin>>(*t).first;
       cout<<"Enter Second: ";
       cin>>(*t).second;
       cout<<endl;
       (*t).next = new (list);
       t = (*t).next;
   }
   
   (*t).id=n;                         //Ïîñëåäíèé ýëåìåíò ñïèñêà
   cout<<"Enter First: ";
   cin>>(*t).first;
   cout<<"Enter Second: ";
   cin>>(*t).second;
   cout<<endl;
   (*t).next = new (list);
   (*t).next = NULL;
   
   system("cls");
//////////////////////////////////////
   
   for (t=phead; t!=NULL; t=(*t).next)
   {
       cout<<"ID: "<<(*t).id<<endl;
       cout<<"Adress: "<<t<<endl;
       cout<<"First: "<<(*t).first<<endl;
       cout<<"Second: "<<(*t).second<<endl;
       cout<<endl;
   }
//////////////////////////////////////
   
   cout<<"Search?"<<endl;
   
   a=getch();
   
   if ((a=='y') || (a=='Y')) 
   {
   system("cls");
   cout<<"Enter ID: ";}
   cin>>n;
          
          for (t=phead; t!=NULL; t=(*t).next)
          { 
              if ( (*t).id==n )
                {system("cls");            
                 cout<<"Your element: "<<endl<<endl;
                 cout<<"ID: "<<(*t).id<<endl;
                 cout<<"Adress: "<<t<<endl;
                 cout<<"First: "<<(*t).first<<endl;
                 cout<<"Second: "<<(*t).second<<endl;}  
          }      
          
   }
}



0



Croessmah

Неэпический

17815 / 10586 / 2044

Регистрация: 27.09.2012

Сообщений: 26,631

Записей в блоге: 1

10.06.2013, 19:20

2

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   if ((a=='y') || (a=='Y')) 
   {//1
   system("cls");
   cout<<"Enter ID: ";}//0
   cin>>n;
          
          for (t=phead; t!=NULL; t=(*t).next)
          { //1
              if ( (*t).id==n )
                {system("cls");  //2          
                 cout<<"Your element: "<<endl<<endl;
                 cout<<"ID: "<<(*t).id<<endl;
                 cout<<"Adress: "<<t<<endl;
                 cout<<"First: "<<(*t).first<<endl;
                 cout<<"Second: "<<(*t).second<<endl;}  //1
          }      //0
          
   }//-1 - откуда она?



1



Lex0R

0 / 0 / 0

Регистрация: 28.03.2013

Сообщений: 5

10.06.2013, 19:23

 [ТС]

3

Цитата
Сообщение от Croessmah
Посмотреть сообщение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   if ((a=='y') || (a=='Y')) 
   {//1
   system("cls");
   cout<<"Enter ID: ";}//0
   cin>>n;
          
          for (t=phead; t!=NULL; t=(*t).next)
          { //1
              if ( (*t).id==n )
                {system("cls");  //2          
                 cout<<"Your element: "<<endl<<endl;
                 cout<<"ID: "<<(*t).id<<endl;
                 cout<<"Adress: "<<t<<endl;
                 cout<<"First: "<<(*t).first<<endl;
                 cout<<"Second: "<<(*t).second<<endl;}  //1
          }      //0
          
   }//-1 - откуда она?

Тьфу ты блин, я уже минут 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

Цитата
Сообщение от Croessmah
Посмотреть сообщение

Можете почитать книгу Уильям Топп, Уильям Форд «Структуры данных в 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

PhysicsLemur's user avatar

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 Ha's user avatar

Dat HaDat Ha

2,9036 gold badges21 silver badges44 bronze badges

Возможно, вам также будет интересно:

  • Ошибка excel введенное значение неверно
  • Ошибка excel runtime error 424
  • Ошибка excel application defined or object defined error 1004
  • Ошибка ex1022 fanuc что делать
  • Ошибка ews на мотоцикле bmw k1200s

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии