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

Hi,
  • 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 ]  

              Понравилась статья? Поделить с друзьями:

              Читайте также:

            • Error c2144 syntax error void should be preceded by
            • Error c2144 syntax error int should be preceded by
            • Error c2143 синтаксическая ошибка отсутствие перед строка
            • Error c2143 синтаксическая ошибка отсутствие перед using namespace
            • Error c2143 синтаксическая ошибка отсутствие перед class head

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

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