Синтаксическая ошибка перед int требуется

Виталий 81

1

03.10.2010, 18:42. Показов 3460. Ответов 2

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


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

кто подскажет как исправить ошибку-1>c:program filesmicrosoft visual studio 10.0vcincludeconio.h(21): error C2144: синтаксическая ошибка: перед «int» требуется «;»
Программа на С++2010

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
// 21.cpp: определяет точку входа для консольного приложения.
 
 
#include "stdafx.h"
#include <iostream>
    using std::cin
#include <conio.h>
 
using namespace std;
//#define N 100
#include <stdio.h>
;int N=100;
;int i,j;
 
;int A[100],B[100];
 
//
void main()
{
using std::endl;
cout<<"Enter elements of array А(numeric):"<<endl;
 for(i = 0; i < N; i++)
 {
   cout<<"A["<<i<<"]=";
   cin>>A[i];
 }
 for(i = N-1, j = 0; i > -1; i--, j++)
 {
   B[j] = A[i];
 }
 for(i = 0; i < N; i++)
 {
   cout<<"A["<<i<<"]="<<A[i];
   cout<<"   ";
   cout<<"B["<<i<<"]="<<B[i];
   cout<<endl;
 
 }
 getch();
}

Bazan

22 / 22 / 4

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

Сообщений: 100

03.10.2010, 18:47

2

Поставьте ; после

C++
1
using std::cin



1



Виталий 81

03.10.2010, 18:56

3

Спасибо БАААльшое за помощь заработала

Виталий 81

1

03.10.2010, 18:42. Показов 3293. Ответов 2

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


кто подскажет как исправить ошибку-1>c:program filesmicrosoft visual studio 10.0vcincludeconio.h(21): error C2144: синтаксическая ошибка: перед «int» требуется «;»
Программа на С++2010

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
// 21.cpp: определяет точку входа для консольного приложения.
 
 
#include "stdafx.h"
#include <iostream>
    using std::cin
#include <conio.h>
 
using namespace std;
//#define N 100
#include <stdio.h>
;int N=100;
;int i,j;
 
;int A[100],B[100];
 
//
void main()
{
using std::endl;
cout<<"Enter elements of array А(numeric):"<<endl;
 for(i = 0; i < N; i++)
 {
   cout<<"A["<<i<<"]=";
   cin>>A[i];
 }
 for(i = N-1, j = 0; i > -1; i--, j++)
 {
   B[j] = A[i];
 }
 for(i = 0; i < N; i++)
 {
   cout<<"A["<<i<<"]="<<A[i];
   cout<<"   ";
   cout<<"B["<<i<<"]="<<B[i];
   cout<<endl;
 
 }
 getch();
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Bazan

22 / 22 / 4

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

Сообщений: 100

03.10.2010, 18:47

2

Поставьте ; после

C++
1
using std::cin

1

Виталий 81

03.10.2010, 18:56

3

Спасибо БАААльшое за помощь заработала

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    Правила раздела Visual C++ / MFC / WTL (далее Раздела)

    >
    Глюки в VS 2008

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    16.01.09, 18:23

      Значит, так:

      Открываю проект, над которым работаю в текущее время.
      Что-то делаю, компилю(release), всплывает :

      Цитата

      Ошибка 1 error C2144: синтаксическая ошибка: перед «int» требуется «;» C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29
      Ошибка 2 error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29

      Смотрю другие проекты. Хоть MFC, хоть Win32 Application, но эта ошибка появляется во всех проектах.
      Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

      Что делать?


      Der_Meister



      Сообщ.
      #2

      ,
      16.01.09, 20:28

        Приложи свой math.h


        n0rd



        Сообщ.
        #3

        ,
        16.01.09, 21:43

          Вот мой math.h, у меня проблем нет. Сравнивай.

          Прикреплённый файлПрикреплённый файлmath.rar (3.57 Кбайт, скачиваний: 61)


          KOMAP



          Сообщ.
          #4

          ,
          17.01.09, 11:21

            n0rd
            Спасибо.

            Появились новые ошибки :

            ExpandedWrap disabled

              IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) //<——- ругается только здесь

            Цитата

            error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «CObject»

            error C2143: синтаксическая ошибка: отсутствие «;» перед «*»

            error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

            error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

            error C2556: int *CChildFrame::CreateObject(void): перегруженная функция отличается от ‘CObject *CChildFrame::CreateObject(void)’ только возвращаемым типом

            error C2371: CChildFrame::CreateObject: переопределение; различные базовые типы


            KOMAP



            Сообщ.
            #5

            ,
            17.01.09, 18:42

              Цитата KOMAP @ 16.01.09, 18:23

              Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

              Эта проблема еще актуальна.

              0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

              0 пользователей:

              • Предыдущая тема
              • Visual C++ / MFC / WTL
              • Следующая тема

              Рейтинг@Mail.ru

              [ Script execution time: 0,0903 ]   [ 16 queries used ]   [ Generated: 31.01.23, 02:10 GMT ]  

                #include <stdlib.h>

                /* подключаем библиотеку GLUT */

                #include <oglglut.h>

                /* начальная ширина и высота окна */

                GLint Width = 512, Height = 512;

                /* размер куба */

                const int CubeSize = 200;

                /* эта функция управляет всем выводом на экран */

                void Display(void)

                {

                    int left, right, top, bottom;

                    left  = (Width — CubeSize) / 2;

                    right = left + CubeSize;

                    bottom = (Height — CubeSize) / 2;

                    top = bottom + CubeSize;

                    glClearColor(0, 0, 0, 1);

                    glClear(GL_COLOR_BUFFER_BIT);

                    glColor3ub(255,0,0);

                    glBegin(GL_QUADS);

                      glVertex2f(left,bottom);

                      glVertex2f(left,top);

                      glVertex2f(right,top);

                      glVertex2f(right,bottom);

                    glEnd();

                    glFinish();

                }

                /* Функция вызывается при изменении размеров окна */

                void Reshape(GLint w, GLint h)

                {

                    Width = w;

                    Height = h;

                    /* устанавливаем размеры области отображения */

                    glViewport(0, 0, w, h);

                    /* ортографическая проекция */

                    glMatrixMode(GL_PROJECTION);

                    glLoadIdentity();

                    glOrtho(0, w, 0, h, -1.0, 1.0);

                    glMatrixMode(GL_MODELVIEW);

                    glutLoadIdentity();

                }

                /* Функция обрабатывает сообщения от клавиатуры */

                void Keyboard(unsigned char key, int x, int y)

                {

                #define ESCAPE ’33’

                    if( key == ESCAPE )

                        exit(0);

                }

                /* Главный цикл приложения */

                main(int argc, char *argv[])

                {

                    glutInit(&argc, argv);

                    glutInitDisplayMode(GLUT_RGB);

                    glutInitWindowSize(Width, Height);

                    glutCreateWindow(«Red square example»);

                    glutDisplayFunc(Display);

                    glutReshapeFunc(Reshape);

                    glutKeyboardFunc(Keyboard);

                    glutMainLoop();

                }

              I’m trying to run a Hello World program but am getting the error

              ./ex1.c: line 3: syntax error near unexpected token `(`
              ./ex1.c: line 3: `int main (int argc, char *argv[])'
              

              or

              ./ex1.c: 3: ./ex1.c: Syntax error: "(" unexpected
              

              or

              ./ex1.c:3: unknown file attribute: i
              ./ex1.c:4: parse error near `}'
              

              The weird thing is I’ve run this same program before and had no issues.

              Not sure if these issues are related but the problem happened after I installed Valgrind to run exercise 4 in Learn C The Hard Way. I received an error that said permission denied which I fixed using chmod +x. Then all my .c files needed permission which they had not before. I then did chmod -R 0777 for the directory with all of my .c practice files. So the permission problem is fixed but then the error above started. They may be completed unrelated but wanted to include just in case.

              Antti Haapala -- Слава Україні's user avatar

              asked Oct 11, 2012 at 2:56

              MParker's user avatar

              4

              You can’t run a .c file just by using ./ex1.c; you have to compile it into a runnable program first.

              Assuming you have a Linux/OS X machine, use gcc -Wall ex1.c -o ex1 to compile it (or, more simply, make ex1). Then you can ./ex1 to run the program.

              answered Oct 11, 2012 at 2:59

              nneonneo's user avatar

              nneonneonneonneo

              168k35 gold badges300 silver badges373 bronze badges

              1

              After you compile the program by using make «your program name» (like make mario in this case), then just use ./»your program name» (this case ./mario). DO NOT add .c when running the program.

              answered Oct 8, 2015 at 19:05

              ThinkTankShark's user avatar

              2

              I’m trying to run a Hello World program but am getting the error

              ./ex1.c: line 3: syntax error near unexpected token `(`
              ./ex1.c: line 3: `int main (int argc, char *argv[])'
              

              or

              ./ex1.c: 3: ./ex1.c: Syntax error: "(" unexpected
              

              or

              ./ex1.c:3: unknown file attribute: i
              ./ex1.c:4: parse error near `}'
              

              The weird thing is I’ve run this same program before and had no issues.

              Not sure if these issues are related but the problem happened after I installed Valgrind to run exercise 4 in Learn C The Hard Way. I received an error that said permission denied which I fixed using chmod +x. Then all my .c files needed permission which they had not before. I then did chmod -R 0777 for the directory with all of my .c practice files. So the permission problem is fixed but then the error above started. They may be completed unrelated but wanted to include just in case.

              Antti Haapala -- Слава Україні's user avatar

              asked Oct 11, 2012 at 2:56

              MParker's user avatar

              4

              You can’t run a .c file just by using ./ex1.c; you have to compile it into a runnable program first.

              Assuming you have a Linux/OS X machine, use gcc -Wall ex1.c -o ex1 to compile it (or, more simply, make ex1). Then you can ./ex1 to run the program.

              answered Oct 11, 2012 at 2:59

              nneonneo's user avatar

              nneonneonneonneo

              168k35 gold badges300 silver badges373 bronze badges

              1

              After you compile the program by using make «your program name» (like make mario in this case), then just use ./»your program name» (this case ./mario). DO NOT add .c when running the program.

              answered Oct 8, 2015 at 19:05

              ThinkTankShark's user avatar

              2


              Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  05.09.13 20:06
              Оценка:

              Доброе утро коллеги. Необходимо работать с HID устройствами. Для этого планирую использовать возможности WDK, однако даже такой элементарный код, как:

              #include "stdafx.h"
              
              extern "C" 
              {
              #include "setupapi.h" 
              #include "hidsdi.h"
              }
              
              int _tmain(int argc, _TCHAR* argv[])
              {
                  GUID HidGuid;
                  HidD_GetHidGuid(&HidGuid);
              
                  return 0;
              }

              при компиляции вызывает кучу ошибок, завершающихся «fatal error C1003: число ошибок превышает 100; остановка компиляции»

              Быть может я не правильно подключил WDK или что еще не сделал?
              Каталоги включения в настройках проекта прописал: «C:WinDDK7600.16385.1incapi;C:WinDDK7600.16385.1incddk;$(IncludePath)». Что еще?


              Re: Работа с HID устройствами WDK

              От:

              pva

               
              Дата:  06.09.13 09:27
              Оценка:

              Здравствуйте, dosik, Вы писали:

              D>Доброе утро коллеги. Необходимо работать с HID устройствами. Для этого планирую использовать возможности WDK, однако даже такой элементарный код, как:

              D>при компиляции вызывает кучу ошибок, завершающихся «fatal error C1003: число ошибок превышает 100; остановка компиляции»
              А какой ошибкой начинается-то?

              newbie


              Re[2]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  06.09.13 10:54
              Оценка:

              Здравствуйте, pva, Вы писали:

              pva>А какой ошибкой начинается-то?

              Вот несколько первых строк:

              1>ClCompile:
              1>  stdafx.cpp
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): error C2065: _In_opt_z_: необъявленный идентификатор
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): error C2143: синтаксическая ошибка: отсутствие ")" перед "const"
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): warning C4229: устаревший элемент: пропуск модификаторов для данных
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): error C2182: _invalid_parameter: недопустимое использование типа "void"
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): error C2491: _invalid_parameter: определение dllimport данные не разрешено
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(543): error C2059: синтаксическая ошибка: )
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2065: _In_opt_z_: необъявленный идентификатор
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2143: синтаксическая ошибка: отсутствие ")" перед "const"
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): warning C4229: устаревший элемент: пропуск модификаторов для данных
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2182: _invoke_watson: недопустимое использование типа "void"
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2495: _invoke_watson: параметр "__declspec(noreturn)" может применяться только в объявлениях или определениях функций
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2491: _invoke_watson: определение dllimport данные не разрешено
              1>c:program files (x86)microsoft visual studio 10.0vcincludecrtdefs.h(550): error C2059: синтаксическая ошибка: )
              1>c:program files (x86)microsoft visual studio 10.0vcincludestdio.h(186): error C2144: синтаксическая ошибка: перед "int" требуется ";"
              1>c:program files (x86)microsoft visual studio 10.0vcincludestdio.h(186): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
              1>c:program files (x86)microsoft visual studio 10.0vcincludestdio.h(186): error C2065: _Inout_: необъявленный идентификатор
              1>c:program files (x86)microsoft visual studio 10.0vcincludestdio.h(186): error C2146: синтаксическая ошибка: отсутствие ")" перед идентификатором "FILE"
              1>c:program files (x86)microsoft visual studio 10.0vcincludestdio.h(186): warning C4229: устаревший элемент: пропуск модификаторов для данных


              Re[3]: Работа с HID устройствами WDK

              От:

              anonymous185

               
              Дата:  06.09.13 10:59
              Оценка:


              Re[4]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  09.09.13 01:50
              Оценка:

              Здравствуйте, anonymous185, Вы писали:

              A>здесь

              Смена очередности каталогов включения не помогла.


              Re[5]: Работа с HID устройствами WDK

              От:

              anonymous185

               
              Дата:  09.09.13 05:40
              Оценка:

              Смена очередности каталогов включения не помогла.

              ну наверно ещё немного думать надо, а не просто очередность включения каталогов менять.
              всё начинается с этой ошибки.

              error C2065: _In_opt_z_: необъявленный идентификатор

              _In_opt_z_ объявляется в <sal.h> . но эти sal.h разные бывают — в некоторых объявляется, в некоторых нет. при решении таких проблем — первое и самое главное выставить опцию /showIncludes в командной строке компилятора. и дальше смотреть — включается ли sal.h, по какому конкретно пути. есть ли в нём #define _In_opt_z_ . может надо не очерёдность каталогов менять, а перезаписать sal.h на другой (где есть _In_opt_z_ определение). или с другой стороны может нужно crt другое(из другого каталога) включать, где нет _In_opt_z_ и подобных макросов. вообщем нужно уметь правильно настроить среду visual studio. и врядли это кто то сделает за вас удалённо.


              Re[6]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  09.09.13 07:51
              Оценка:

              Здравствуйте, anonymous185, Вы писали:

              A>вообщем нужно уметь правильно настроить среду visual studio. и врядли это кто то сделает за вас удалённо.

              Вот по этому я сюда и обращаюсь за помощью, чтобы хотя бы вектор изучения указали.


              Re[7]: Работа с HID устройствами WDK

              От:

              anonymous185

               
              Дата:  09.09.13 08:45
              Оценка:

              Вот по этому я сюда и обращаюсь за помощью, чтобы хотя бы вектор изучения указали.

              /showIncludes и думать


              Re[8]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  09.09.13 11:06
              Оценка:

              Здравствуйте, anonymous185, Вы писали:

              A>

              A>Вот по этому я сюда и обращаюсь за помощью, чтобы хотя бы вектор изучения указали.

              A>/showIncludes и думать

              OK. Подскажите в таком случае что я там должен увидеть и на что обратить внимание?


              Re[9]: Работа с HID устройствами WDK

              От:

              anonymous185

               
              Дата:  09.09.13 12:40
              Оценка:

              что я там должен увидеть

              все включаемые файлы с полными путями.

              что обратить внимание?

              ну на sal.h например. включается ? думаю да. его полный путь. есть в нём #define _In_opt_z_ ? — думаю нет. скорей всего нужно взять другой sal.h и скопировать его поверх включаемого. вообще нужно уметь думать как компилятор. стать на его место и взглянуть на ситуацию его глазами. он ведь ясно говорит — я незнаю что такое _In_opt_z_, не вижу его определения. значит вам самому надо узнать где _In_opt_z_ определён (в каком h-файле) далее посмотреть включается ли этот файл, тот ли (для этого и сверхполезна опция /showIncludes ) ну и предринять какие то действия чтобы правильный файл включался — добавить вручную, поменять очерёдность include путей, отредактировать(перезаписать) файл.. возможно кроме этой будут и другие ошибки/проблемы — опять таки есть только одно решение — думать(как компилятор (ну или как компоновщик если ошибки на этапе линковки) )


              Re[10]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  09.09.13 14:40
              Оценка:

              Здравствуйте, anonymous185, Вы писали:

              A>

              что я там должен увидеть

              A>все включаемые файлы с полными путями.
              A>

              что обратить внимание?

              A>ну на sal.h например. включается ? думаю да. его полный путь. есть в нём #define _In_opt_z_ ? — думаю нет. скорей всего нужно взять другой sal.h и скопировать его поверх включаемого. вообще нужно уметь думать как компилятор. стать на его место и взглянуть на ситуацию его глазами. он ведь ясно говорит — я незнаю что такое _In_opt_z_, не вижу его определения. значит вам самому надо узнать где _In_opt_z_ определён (в каком h-файле) далее посмотреть включается ли этот файл, тот ли (для этого и сверхполезна опция /showIncludes ) ну и предринять какие то действия чтобы правильный файл включался — добавить вручную, поменять очерёдность include путей, отредактировать(перезаписать) файл.. возможно кроме этой будут и другие ошибки/проблемы — опять таки есть только одно решение — думать(как компилятор (ну или как компоновщик если ошибки на этапе линковки) )

              Не думаю что так все глубоко (перезапись файлов и т.п.), нашелся в инете проект, который работает с HID устройствами этими же функция, и компилиться и собирается на ура. Вроде все настройки сравнил со своим, а все равно, найденный проект компилиться, мой нет (((


              Re[11]: Работа с HID устройствами WDK

              От:

              dosik

              Россия

              www.dosik.ru
              Дата:  09.09.13 16:04
              Оценка:

              Я же говорил что все банально.

              Не хватало:

              #include <iostream>
              #include <Windows.h>
              #pragma comment (lib, "hid.lib")

              Спасибо огромное за уделенное время.

              Подождите ...

              Wait...

              • Переместить
              • Удалить
              • Выделить ветку

              Пока на собственное сообщение не было ответов, его можно удалить.

              Я пытаюсь скомпилировать этот код на C++:

              #include <stdlib.h>
              #include <stdio.h>   
              #include <string.h>
              #include "general_configuration.h"
              #include "helper_functions.h"
              
              #define LINE_LEN 80
              
              // file_with_as_ext returns 1 if the input has .as extension
              int file_with_as_ext(char* input)
              {
                char* dot_value = strchr(input, '.');
                if (dot_value == NULL)
                  return 0;
                else
                {
                  if (strcmp(dot_value,".as") == 0)
                    return 1;
                }
              }
              

              но я получаю ошибку "C2144: syntax error : 'int' should be preceded by ';'"
              И я не могу понять, почему, #define не нужно ‘; ‘ в конце.

              любые ides?

              3 ответов


              во-первых, код, который вы разместили, начинается с блуждающей палочки. Если это действительно в вашем коде, вы должны удалить его.

              во-вторых, компилятор будет счастливее и выдаст меньше предупреждений, если вы закончите свою функцию строкой

              return 0; // unreachable
              

              это хороший стиль C++ и рекомендуется. (В вашем случае строка может быть достижим, в этом случае линия не только хороший стиль, но и необходима для правильной работы. Проверять этот.)

              в противном случае ваш код выглядит нормально, за исключением некоторых небольших возражений, которые можно было бы поднять относительно устаревшего использования #define и относительно одной или двух других второстепенных точек стиля. Относительно #define, это не исходный код C++ как таковой, но является директивы препроцессора. он фактически обрабатывается другой программой, чем компилятор, и удаляется и заменяется правильным кодом C++, прежде чем компилятор увидит его. Препроцессор не интересует точка с запятой. Вот почему #define строка не заканчивается точкой с запятой. Как и другие строки, которые начинаются # обычно заканчивается точкой с запятой.

              как отметил @JoachimIsaksson, в конце файла может отсутствовать точка с запятой general_configuration.h или . Вы должны проверить последнюю строку в каждом файле.


              Я столкнулся с этой проблемой. Я написал файл заголовка, но забыл добавить «;» в конце удаления функции. Итак, в моем файле c есть ошибка, которая включает этот файл заголовка.
              Я добавляю комментарий здесь, и надеюсь, что это будет полезно для кого-то.


              и я не могу понять, почему, #define не нужно ‘; ‘ в конце.

              потому что #define-это не оператор, а директивы препроцессора, и препроцессор ориентирован на линию, когда дело доходит до разделения директив. Например, нельзя поместить два # defines в одну строку.


              First, the code you have posted begins with a stray backtick. If that’s really in your code, you should remove it.

              Second, the compiler would be happier, and emit fewer warnings, if you ended your function with the line

              return 0; // unreachable
              

              This is good C++ style and is recommended. (In your case, the line may actually be reachable, in which case the line is not only good style but necessary for correct operation. Check this.)

              Otherwise, your code looks all right except for some small objections one could raise regarding the outdated, C-style use of #define and regarding one or two other minor points of style. Regarding the #define, it is not C++ source code as such but is a preprocessor directive. It is actually handled by a different program than the compiler, and is removed and replaced by proper C++ code before the compiler sees it. The preprocessor is not interested in semicolons. This is why the #define line does not end in a semicolon. Neither do other lines that begin # usually end in semicolons.

              As @JoachimIsaksson has noted, a needed semicolon may be missing from the end of the file general_configuration.h or the file helper_function.h. You should check the last line in each file.

              • Remove From My Forums
              • Question

              • Hi,

                Please help by give me some clues on the following…

                When I build my project, everything compiles fine except the following lines :

                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C2144: syntax error : ‘int’ should be preceded by ‘;’
                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C4430: missing type specifier — int assumed. Note: C++ does not support
                default-int

                If I follow the output message it takes me to sal.h with the ‘error pointer’
                on the extern «C» line.

                #ifdef __cplusplus
                #ifndef __nothrow
                # define __nothrow __declspec(nothrow)
                #endif
                extern «C» { // C2144
                #else
                #ifndef __nothrow
                # define __nothrow
                #endif
                #endif /* #ifdef __cplusplus */

                I haven’t touched this file at all, I was just working on my projects concerned file, so i have no
                idea what is causing this error.

                WinXP, MS VS2005.

                Any suggestions gratefully recieved.

                Regards,

                Techies

              First, the code you have posted begins with a stray backtick. If that’s really in your code, you should remove it.

              Second, the compiler would be happier, and emit fewer warnings, if you ended your function with the line

              return 0; // unreachable
              

              This is good C++ style and is recommended. (In your case, the line may actually be reachable, in which case the line is not only good style but necessary for correct operation. Check this.)

              Otherwise, your code looks all right except for some small objections one could raise regarding the outdated, C-style use of #define and regarding one or two other minor points of style. Regarding the #define, it is not C++ source code as such but is a preprocessor directive. It is actually handled by a different program than the compiler, and is removed and replaced by proper C++ code before the compiler sees it. The preprocessor is not interested in semicolons. This is why the #define line does not end in a semicolon. Neither do other lines that begin # usually end in semicolons.

              As @JoachimIsaksson has noted, a needed semicolon may be missing from the end of the file general_configuration.h or the file helper_function.h. You should check the last line in each file.

              Виталий 81

              1

              03.10.2010, 18:42. Показов 3317. Ответов 2

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


              кто подскажет как исправить ошибку-1>c:program filesmicrosoft visual studio 10.0vcincludeconio.h(21): error C2144: синтаксическая ошибка: перед «int» требуется «;»
              Программа на С++2010

              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
              
              // 21.cpp: определяет точку входа для консольного приложения.
               
               
              #include "stdafx.h"
              #include <iostream>
                  using std::cin
              #include <conio.h>
               
              using namespace std;
              //#define N 100
              #include <stdio.h>
              ;int N=100;
              ;int i,j;
               
              ;int A[100],B[100];
               
              //
              void main()
              {
              using std::endl;
              cout<<"Enter elements of array А(numeric):"<<endl;
               for(i = 0; i < N; i++)
               {
                 cout<<"A["<<i<<"]=";
                 cin>>A[i];
               }
               for(i = N-1, j = 0; i > -1; i--, j++)
               {
                 B[j] = A[i];
               }
               for(i = 0; i < N; i++)
               {
                 cout<<"A["<<i<<"]="<<A[i];
                 cout<<"   ";
                 cout<<"B["<<i<<"]="<<B[i];
                 cout<<endl;
               
               }
               getch();
              }

              __________________
              Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

              Bazan

              22 / 22 / 4

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

              Сообщений: 100

              03.10.2010, 18:47

              2

              Поставьте ; после

              C++
              1
              
              using std::cin

              1

              Виталий 81

              03.10.2010, 18:56

              3

              Спасибо БАААльшое за помощь заработала

              • Forum
              • Beginners
              • Error C2144 and error C4430

              Error C2144 and error C4430

              First of all I realise that there are a number of posts about this error and they all describe how there is usually a semicolon missing before the error mentioned line, and in some cases they are refering to a different header file.

              While I am not eliminating the possibility of my problem being a semicolon that I have missed, but it is not one that I have been able to find.

              Now to the error, as the title suggests I am getting the error C2144 «syntax error: ‘int’ should be preceded by ‘;’» and error C4430 «missing type specifier — int assumed. Note: C++ does not support default-int» on lines 12 and 19 respectively in my Piece header file. (Note I am getting both errors on both lines, I have marked them in my code)

              Piece.h

              1
              2
              3
              4
              5
              6
              7
              8
              9
              10
              11
              12
              13
              14
              15
              16
              17
              18
              19
              20
              21
              #ifndef PIECE_H
              #define PIECE_H
              #include <string>
              
              //abstract/base class
              class Piece {
              public:
              	bool static kingSafe(); //Check if king is safe
              	string static currentPosition(); //---Error
              };
              
              class Pawn : public Piece // derive class Pawn from class Piece 
              {
              public:
              	//bool isWhite(); //Determine which direction pawn can move in based on if it is White or Black
              	string static legalMoveP(int); //---Error--
              
              };
              
              
              #endif 

              Thank you for your help.

              Last edited on

              Are those the only errors/warnings being generated by your compiler?

              Did you perhaps forget to #include a necessary #include file or perhaps forgot to properly scope something from the std namespace?

              Hello Arooom,

              Welcome to the forum.

              Missing the header file and main, so I can not compile your program to see what is happening. I do get the 4430 error because of the missing header file. It says that JustABoard in JustABoard CurrentGame is not a type and that «int» is assumed and the rest.

              Now to the error, as the title suggests I am getting the error C2144 «syntax error: ‘int’ should be preceded by ‘;’»

              This is nice, but what line in which file does this refer to. You have left out important information. It is best to include the whole error message with line numbers and file.

              Right now I can not duplicate your errors with out all the files and with the 127 error messages I do get some direct me to the «board.h» header file I do not have.

              Not knowing what main looks like I can not say if any of your errors start there.

              It is best to include all the files, because sometimes the error is not always where you think it is.

              Hope that helps,

              Andy

              @jlb No I I receive other warnings when I try to compile but I do assume that they are connected to the errors stated above.

              @Handy Andy Thank you for your reply. I did state that the errors are on line 12 and 19 of my header file that I included. I also included an edited cpp file with only relevant code to the problem so as I don’t spam the post with code. I did not think others would like to compile to see the problem for themselves.

              Last edited on

              Lines 12 and 19? What is a «string»?

              1
              2
              3
              4
              5
              6
              7
              8
              9
              10
              11
              12
              13
              14
              15
              16
              #ifndef PIECE_H
              #define PIECE_H
              #include <string>
              
              // base class
              struct Piece {
              	static bool kingSafe();
              	static std::string currentPosition();
              };
              
              struct Pawn : public Piece
              {
              	static std::string legalMoveP(int);
              };
              
              #endif 

              Sorry, I use

              because I’m not used to coding without it yet. I’m new to programming, even more to C++.

              As to if you are suggesting to me to switch the location of «static» and «std::string», then it still results in an error for me. » Error C3646: unknown override specifier «, » Error C2059: syntax error: ‘)’ » and » Error C2238: unexpected token(s) preceding ‘;’ » on both line 12 and 19 again.

              Last edited on

              I hope you’re not using that statement inside the header file which is where the problem is occurring!

              And note your code posted in post #1 does not (thankfully) have the using statement in that header.

              I can’t believe I missed that, and I will try to avoid using it.
              Thank you for your help.

              Hello Arooom,

              Thank you for the files they are just what I needed.

              Sometimes it helps me to have all the files, so I can see exactly what is happening. And complete files make a big difference. I am good, but some programs just need the long way around.

              Sorry after I posted the message I did find the comments on the lines 12 and 19. Speaking of those lines I did figure that you need to qualify «string» with «std::». Once I did that the program compiled.

              Before you think of adding the line using namespace std:: to your header files read this: http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

              I did have four warnings that variables «k» and «p» in the Definitions file are «unreferenced local variable»s. This generally means that you defined a variable, but never used it even though I see it being used in the while condition at the bottom of the function. These are only warnings for me. Nothing to stop it from compiling, but may be a problem at run time.

              Hope that helps,

              Andy

              Hello Arooom,

              I saw the other posts after I finished mine.

              Sorry, I use
              «using namespace std;»
              because I’m not used to coding without it yet. I’m new to programming, even more to C++.

              Now is the best time to learn when it is a little at a time instead of all at once later.

              Andy

              Topic archived. No new replies allowed.

              • Remove From My Forums
              • Question

              • Hi,

                Please help by give me some clues on the following…

                When I build my project, everything compiles fine except the following lines :

                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C2144: syntax error : ‘int’ should be preceded by ‘;’
                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C4430: missing type specifier — int assumed. Note: C++ does not support
                default-int

                If I follow the output message it takes me to sal.h with the ‘error pointer’
                on the extern «C» line.

                #ifdef __cplusplus
                #ifndef __nothrow
                # define __nothrow __declspec(nothrow)
                #endif
                extern «C» { // C2144
                #else
                #ifndef __nothrow
                # define __nothrow
                #endif
                #endif /* #ifdef __cplusplus */

                I haven’t touched this file at all, I was just working on my projects concerned file, so i have no
                idea what is causing this error.

                WinXP, MS VS2005.

                Any suggestions gratefully recieved.

                Regards,

                Techies

              • Remove From My Forums
              • Question

              • Hi,

                Please help by give me some clues on the following…

                When I build my project, everything compiles fine except the following lines :

                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C2144: syntax error : ‘int’ should be preceded by ‘;’
                C:Program FilesMicrosoft Visual Studio 8VCincludesal.h(226) : error
                C4430: missing type specifier — int assumed. Note: C++ does not support
                default-int

                If I follow the output message it takes me to sal.h with the ‘error pointer’
                on the extern «C» line.

                #ifdef __cplusplus
                #ifndef __nothrow
                # define __nothrow __declspec(nothrow)
                #endif
                extern «C» { // C2144
                #else
                #ifndef __nothrow
                # define __nothrow
                #endif
                #endif /* #ifdef __cplusplus */

                I haven’t touched this file at all, I was just working on my projects concerned file, so i have no
                idea what is causing this error.

                WinXP, MS VS2005.

                Any suggestions gratefully recieved.

                Regards,

                Techies

              Во-первых, код, который вы опубликовали, начинается с блуждающего обратного хода. Если это действительно в вашем коде, вы должны удалить его.

              Во-вторых, компилятор будет более счастливым и выпустит меньше предупреждений, если вы закончите свою функцию с помощью строки

              return 0; // unreachable
              

              Это хороший стиль С++ и рекомендуется. (В вашем случае линия действительно может достижима, и в этом случае линия не только хороша, но и необходима для правильной работы. Проверьте это.)

              В противном случае ваш код выглядит правильно, за исключением некоторых небольших возражений, которые можно было бы повысить относительно устаревшего использования стиля #define в стиле C и в отношении одной или двух других второстепенных точек стиля. Что касается #define, это не исходный код С++ как таковой, а директива препроцессора. Он фактически обрабатывается другой программой, чем компилятор, и удаляется и заменяется соответствующим кодом на С++, прежде чем компилятор увидит его. Препроцессор не интересуется точкой с запятой. Вот почему строка #define не заканчивается точкой с запятой. Другие строки, начинающиеся с #, обычно заканчиваются точкой с запятой.

              Как отметил @JoachimIsaksson, нужная точка с запятой может отсутствовать в конце файла general_configuration.h или файла helper_function.h. Вы должны проверить последнюю строку в каждом файле.

                msm.ru

                Нравится ресурс?

                Помоги проекту!

                !
                Правила раздела Visual C++ / MFC / WTL (далее Раздела)

                >
                Глюки в VS 2008

                • Подписаться на тему
                • Сообщить другу
                • Скачать/распечатать тему



                Сообщ.
                #1

                ,
                16.01.09, 18:23

                  Значит, так:

                  Открываю проект, над которым работаю в текущее время.
                  Что-то делаю, компилю(release), всплывает :

                  Цитата

                  Ошибка 1 error C2144: синтаксическая ошибка: перед «int» требуется «;» C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29
                  Ошибка 2 error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29

                  Смотрю другие проекты. Хоть MFC, хоть Win32 Application, но эта ошибка появляется во всех проектах.
                  Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

                  Что делать?


                  Der_Meister



                  Сообщ.
                  #2

                  ,
                  16.01.09, 20:28

                    Приложи свой math.h


                    n0rd



                    Сообщ.
                    #3

                    ,
                    16.01.09, 21:43

                      Вот мой math.h, у меня проблем нет. Сравнивай.

                      Прикреплённый файлПрикреплённый файлmath.rar (3.57 Кбайт, скачиваний: 62)


                      KOMAP



                      Сообщ.
                      #4

                      ,
                      17.01.09, 11:21

                        n0rd
                        Спасибо.

                        Появились новые ошибки :

                        ExpandedWrap disabled

                          IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) //<——- ругается только здесь

                        Цитата

                        error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «CObject»

                        error C2143: синтаксическая ошибка: отсутствие «;» перед «*»

                        error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

                        error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

                        error C2556: int *CChildFrame::CreateObject(void): перегруженная функция отличается от ‘CObject *CChildFrame::CreateObject(void)’ только возвращаемым типом

                        error C2371: CChildFrame::CreateObject: переопределение; различные базовые типы


                        KOMAP



                        Сообщ.
                        #5

                        ,
                        17.01.09, 18:42

                          Цитата KOMAP @ 16.01.09, 18:23

                          Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

                          Эта проблема еще актуальна.

                          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                          0 пользователей:

                          • Предыдущая тема
                          • Visual C++ / MFC / WTL
                          • Следующая тема

                          Рейтинг@Mail.ru

                          [ Script execution time: 0,0998 ]   [ 16 queries used ]   [ Generated: 9.02.23, 12:12 GMT ]  

                            msm.ru

                            Нравится ресурс?

                            Помоги проекту!

                            !
                            Правила раздела Visual C++ / MFC / WTL (далее Раздела)

                            >
                            Глюки в VS 2008

                            • Подписаться на тему
                            • Сообщить другу
                            • Скачать/распечатать тему



                            Сообщ.
                            #1

                            ,
                            16.01.09, 18:23

                              Значит, так:

                              Открываю проект, над которым работаю в текущее время.
                              Что-то делаю, компилю(release), всплывает :

                              Цитата

                              Ошибка 1 error C2144: синтаксическая ошибка: перед «int» требуется «;» C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29
                              Ошибка 2 error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию C:Program FilesMicrosoft Visual Studio 9.0VCincludemath.h 29

                              Смотрю другие проекты. Хоть MFC, хоть Win32 Application, но эта ошибка появляется во всех проектах.
                              Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

                              Что делать?


                              Der_Meister



                              Сообщ.
                              #2

                              ,
                              16.01.09, 20:28

                                Приложи свой math.h


                                n0rd



                                Сообщ.
                                #3

                                ,
                                16.01.09, 21:43

                                  Вот мой math.h, у меня проблем нет. Сравнивай.

                                  Прикреплённый файлПрикреплённый файлmath.rar (3.57 Кбайт, скачиваний: 65)


                                  KOMAP



                                  Сообщ.
                                  #4

                                  ,
                                  17.01.09, 11:21

                                    n0rd
                                    Спасибо.

                                    Появились новые ошибки :

                                    ExpandedWrap disabled

                                      IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) //<——- ругается только здесь

                                    Цитата

                                    error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «CObject»

                                    error C2143: синтаксическая ошибка: отсутствие «;» перед «*»

                                    error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

                                    error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию

                                    error C2556: int *CChildFrame::CreateObject(void): перегруженная функция отличается от ‘CObject *CChildFrame::CreateObject(void)’ только возвращаемым типом

                                    error C2371: CChildFrame::CreateObject: переопределение; различные базовые типы


                                    KOMAP



                                    Сообщ.
                                    #5

                                    ,
                                    17.01.09, 18:42

                                      Цитата KOMAP @ 16.01.09, 18:23

                                      Создать проект -> MFC -> MDI Application -> … -> Finish. После всего этого появляется окно «Создать проект». А в папке с проектами есть нужный, но полупустой(без солюшена и т.д.).

                                      Эта проблема еще актуальна.

                                      0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                      0 пользователей:

                                      • Предыдущая тема
                                      • Visual C++ / MFC / WTL
                                      • Следующая тема

                                      Рейтинг@Mail.ru

                                      [ Script execution time: 0,0251 ]   [ 16 queries used ]   [ Generated: 27.06.23, 22:08 GMT ]  

                                    • Синтаксическая ошибка параметра командной строки введите команду для получения справки
                                    • Синтаксическая ошибка параметр ограничиватьдоступнауровнезаписей не существует
                                    • Синтаксическая ошибка параметр не инициализирован
                                    • Синтаксическая ошибка при установке приложения на андроид что это значит
                                    • Синтаксическая ошибка отсутствует операнд после оператора