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-intIf 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
- 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
|
|
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»?
|
|
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.
#include "stdafx.h"
#include <iostream>
int GetUserInput()
{
std::cout << "Please enter in an integer " << std::endl;
int nValue;
std::cin >> nValue;
return nValue;
}
int GetMathematicalOperator()
{
std::cout << "Please enter in the operator you want(1. = +, 2 = -, 3 = *, 4 = /): " << std::endl;
int n0perator;
std::cin >> n0perator;
//If a user enters in a number not in there it returns -1.
return -1;
}
int CalculateResult(int nX, int n0perator, int nY)
{
//calculating what they entered into userinput() and mathematicaloperator()
if(n0perator == 1)
return nX + nY;
if(n0perator == 2)
return nX - nY;
if(n0perator == 3)
return nX * nY;
if(n0perator == 4)
return nX / nY;
return -1;
}
void PrintResult(int nResult)
{
std::cout << "Your result is: " << nResult << std::endl;
}
int main()
{
//Get first number
int nInput1 = GetUserInput();
//Get mathematical operator
int n0perator = GetMathematicalOperator();
//Get second number
int nInput2 = GetUserInput();
//Calculate result and store in temporary variable(for readability/debugability)
int nResult = CalculateResult(int nInput1, int n0perator, int nInput2);
//print result
PrintResult(nResult);
}
I really need help with this. The 3 errors are C2144, C2660, C2059. The first one is mentioned in the title. The second is calculateresult not taking on 0 arguments. The last one is just a syntax error of ‘)’. I’m new to C++ and it took me about an hour to do this. I have no clue how to fix it!
Во-первых, код, который вы опубликовали, начинается с блуждающего обратного хода. Если это действительно в вашем коде, вы должны удалить его.
Во-вторых, компилятор будет более счастливым и выпустит меньше предупреждений, если вы закончите свою функцию с помощью строки
return 0; // unreachable
Это хороший стиль С++ и рекомендуется. (В вашем случае линия действительно может достижима, и в этом случае линия не только хороша, но и необходима для правильной работы. Проверьте это.)
В противном случае ваш код выглядит правильно, за исключением некоторых небольших возражений, которые можно было бы повысить относительно устаревшего использования стиля #define
в стиле C и в отношении одной или двух других второстепенных точек стиля. Что касается #define
, это не исходный код С++ как таковой, а директива препроцессора. Он фактически обрабатывается другой программой, чем компилятор, и удаляется и заменяется соответствующим кодом на С++, прежде чем компилятор увидит его. Препроцессор не интересуется точкой с запятой. Вот почему строка #define
не заканчивается точкой с запятой. Другие строки, начинающиеся с #
, обычно заканчиваются точкой с запятой.
Как отметил @JoachimIsaksson, нужная точка с запятой может отсутствовать в конце файла general_configuration.h
или файла helper_function.h
. Вы должны проверить последнюю строку в каждом файле.
|
|
|
Правила раздела Visual C++ / MFC / WTL (далее Раздела)
Установил VS2005 — не могу откомпилить простую программу
, includesal.h(226) : error C2144:
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Установил только что VS2005 Pro (лицензионная) |
Алкаш |
|
Oleg2004, а на другой студии компилиться? Цитата This error may be caused by a missing closing brace, right parenthesis, or semicolon. Может что-то случано стёр/поставил лишнее? Добавлено 17.10.07, 13:55 |
Алкаш |
|
Цитата Oleg2004 @ 17.10.07, 13:57 Более того — это единственная ошибка, и в каком-то левом хедере sal.h в ссылке пишут что строка 226 — это первая компилируемая строка в этом проекте, поэтому ошибка — в последней строке предыдущего хидера. |
Oleg2004 |
|
Это что значит — в хедере #include <winsock.h> ошибка??? |
Повстанець |
|
Senior Member Рейтинг (т): 63 |
а после int main() точка с запятой разве не должна быть?? |
Oleg2004 |
|
Ничего не изменилось |
Hryak |
|
Цитата Oleg2004 @ 17.10.07, 13:57 Вот начало:
// TCP Server.cpp : Defines the entry point for the console application. int main() #include <winsock.h> #define PORTNUM 5000 #define MAX_PENDING_CONNECTS 5 // Максимальная длина очереди подключений int main(void) { int main() — это что такое? |
Oleg2004 |
|
Цитата Allexx @ 17.10.07, 14:06 а после int main() точка с запятой разве не должна быть?? Нет |
Повстанець |
|
Senior Member Рейтинг (т): 63 |
попробуй убрать первую, после комментов строчку, она там не нужна. А, не, сорри, ошибки быть не должно Сообщение отредактировано: Allexx — 17.10.07, 14:11 |
Oleg2004 |
|
Цитата Hryak @ 17.10.07, 14:07 int main() — это что такое?
Обычный сишный main() |
Hryak |
|
Цитата Oleg2004 @ 17.10.07, 14:10 Цитата Hryak @ 17.10.07, 14:07 int main() — это что такое?
Обычный сишный main() Ты не понял. Я про первую такую строчку говорю. |
Повстанець |
|
Senior Member Рейтинг (т): 63 |
А код полностью можно, написал то же самое — ошибок не выдаёт, хотя вижула та же и без всяких патчей.. |
Oleg2004 |
|
Hryak Цитата Цитата Блиииииииииииииииииин |
LuckLess |
|
есть сервис пак. |
Oleg2004 |
|
LuckLess |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0846 ] [ 16 queries used ] [ Generated: 9.02.23, 12:12 GMT ]
Ошибка C2144: ошибка грамматики: «int» должна быть «;»; »;
C++- error C2144 syntax error : ‘int’ should be preceded by ‘;’
Примечание:я используюVS2010я встретилвопрос。
Решение
В определенном файле .h, последний «;«, Ты должен его использоватьКитайский метод ввода«Под»;«, Изменить это наМетод ввода английского языка,войти»;«.задача решена.
Уведомление:
китайский язык«Под методом ввода»;«а такжеАнглийский«Под методом ввода»;«Это так похоже.
Пример
ошибкапрограмма
main.cpp
#include <iostream>
#include "helloworld.h"
int main(void)
{
HelloWorld hello;
hello.say();
while(1){}
return 0;
}
helloworld.h
#ifndef __HELLOWORLD_H_
#define __HELLOWORLD_H_
class HelloWorld{
public:
HelloWorld(){}
void say(){
std::cout << "Hello World!" << std::endl;
}
};
#endif
Компиляцияпотерпеть неудачу:
1> main.cpp: ошибка C2144: грамматическая ошибка: "int«Перед ним должно быть»; »;»; »;
1>
1> Неудача.
После модификацииправильныйпрограмма
Исправлятьhelloworld.h
#ifndef __HELLOWORLD_H_
#define __HELLOWORLD_H_
class HelloWorld{
public:
HelloWorld(){}
void say(){
std::cout << "Hello World!" << std::endl;
}
};
#endif
Компиляцияуспех:
1> Успешное поколение.
Уведомление:
Другое решение,(но яНе рекомендуется):существуетmain.cppизmain()Функция возврата переменной
int
Добавить «;
«. Это также может решить проблему.#include <iostream> #include "helloworld.h" ;int main(void) { HelloWorld hello; hello.say(); while(1){} return 0; }
Справочный сайт:
1. http://stackoverflow.com/questions/11808432/c-error-c2144-syntax-error-int-should-be-preceded-by