Содержание
- Часто встречающиеся ошибки стадии компиляции
- Thread: Parse error before
- Parse error before
Часто встречающиеся ошибки стадии компиляции
Очень часто начинающие программисты впадают в суеверный ужас, когда видят, что компилятор нашел в тексте программы ошибку, но не понимают, в чем она заключается.
А если помножить этот факт на незнание английского языка («чего там ему не нравится. ») и слабое владение синтаксисом C++ («хм, а может, тут нужна точка с запятой…»), то проблема принимает масштаб катастрофы.
Тот факт, что компилятор в силу своих ограниченных возможностей изо всех сил старается объяснить, что конкретно неверно, не спасает ситуацию. Как быть, если гуглить неохота, а спросить не у кого?
В этом посте на правах копипаста с последующим переводом, дополнениями и исправлениями приведу описание наиболее распространенных сообщений об ошибках и предупреждений компилятора. Неприятность кроется в том факте, что разные компиляторы ругаются на одинаковые ошибки по-разному, а некоторые даже не замечают то, что другие принимают за ошибку. Все зависит от совести разработчиков компилятора, даты его выпуска, и др.
В качестве компилятора возьмем g++, который, в частности, может использоваться в среде Code::Blocks. Версия gcc (куда входит g++) для ОС Windows зовется MinGW. По ходу я буду давать аналоги ошибок из лексикона русскоязычной Microsoft Visual C++.
Итак, частые ошибки:
undeclared identifier
doy.cpp: In function ‘int main()’:
doy.cpp:25: ‘DayOfYear’ undeclared (first use this function)
doy.cpp:25: (Each undeclared identifier is reported only once for each function it appears in.)
doy.cpp:25: parse error before ‘;’ token
2) Смысл
Использован идентификатор DayOfYear , но компилятор не нашел его объявления. Он не знает, что такое DayOfYear .
- Вы забыли включить какой-то заголовочный файл ( #include. )
- Вы где-то ошиблись в написании идентификатора (при объявлении или использовании)
- Вы вообще забыли, что эту переменную надо объявить
Попытавшись скомпилировать это в Microsoft Visual C++, вы увидите:
error C2065: DayOfYear: необъявленный идентификатор
cout undeclared
xyz.cpp: In function ‘int main()’:
xyz.cpp:6: ‘cout’ undeclared (first use this function)
xyz.cpp:6: (Each undeclared identifier is reported only once for each function it appears in.)
2) Смысл
Суперклассика. Без комментариев.
- Вы забыли включить
- Вы забыли написать using namespace std;
jump to case label
switch.cpp: In function ‘int main()’:
switch.cpp:14: jump to case label
switch.cpp:11: crosses initialization of ‘int y’
2) Смысл
Смысл туманен
3) Когда бывает
Вы попытались объявить и инициализировать переменную (объект, указатель и т.п.) в метке case оператора выбора switch. Правилами C++ это запрещено.
В Microsoft Visual C++ эта ошибка зовется
error C2360: пропуск инициализации ‘y’ из-за метки ‘case’
Выход: заключите операторы этого case’а в фигурные скобки <>.
multi-line string / unterminated string
using namespace std;
вызовет бурную реакцию компилятора:
string.cpp:7:12: warning: multi-line string literals are deprecated
string.cpp: In function ‘int main()’:
string.cpp:7: ‘so’ undeclared (first use this function)
string.cpp:7: (Each undeclared identifier is reported only once for each function it appears in.)
string.cpp:7: parse error before ‘Mary’
string.cpp:8:28: warning: multi-line string literals are deprecated
string.cpp:8:28: missing terminating » character
string.cpp:7:12: possible start of unterminated string literal
2) Смысл
Компилятор думает, что мы хотим создать строковую константу с содержащимся в ней переносом строки, что-то типа
что не поддерживается языком. Также делается предположение о том, что мы, возможно, забыли поставить кавычки в конце первой строки. Собственно, так оно и есть.
3) Когда бывает
Когда не соблюдается правильное количество и положение кавычек в строковых литералах. Надо быть внимательнее.
Microsoft Visual C++ со свойственной ему детской непосредственностью, отметит, что нельзя делать переносы в строках и возмутится, где точка с запятой:
error C2001: newline в константе
error C2146: синтаксическая ошибка: отсутствие «;» перед идентификатором «cout»
comparison between signed and unsigned integer expressions
xyz.cpp: In function ‘int main()’:
xyz.cpp:54: warning: comparison between signed and unsigned integer expressions
2) Смысл
Это — предупреждение компилятора, которое говорит о том, что мы пытаемся сравнить (==, и т.д.) целочисленное выражение (может принимать положительные, отрицательные значения и 0) и беззнаковое целочисленное выражение (может быть только положительным, либо 0).
3) Когда бывает
Собственно, тогда и бывает. Напомню, что тип int по умолчанию знаковый, а некоторые функции (например, vector::size() ) возвращают unsigned int .
К примеру, следующий на первый взгляд безобидный код вызовет описываемое предупреждение:
Следует помнить, что в памяти знаковые и беззнаковые типы имеют разные внутренние представления, поэтому надо быть чертовски осторожными с указателями.
В Microsoft Visual C++ предупреждение выглядит так:
suggest parentheses around assignment used as truth value
xyz.cpp: In function `int main()’:
xyz.cpp:54: warning: suggest parentheses around assignment used as truth value
2) Смысл
Тоже классика. Компилятор предполагает (и в 99% случаев прав), что вы по ошибке включили в скобки в качестве условия для if/while/for вместо условного выражения выражение присваивания.
3) Когда бывает
Чаще всего — в if ‘ах, когда вместо «==» используется «=»
if (length = maxLength)
if (length == maxLength)
Заминка в том, что это не ошибка, т.к. в скомпилированной программе (если мы проигнорируем предупреждение) выражение присваивания (которое возвращает значение правого аргумента) во всех случаях, кроме тех, когда оно вернет 0 , будет преобразовано к true .
Источник
Thread: Parse error before
Thread Tools
Search Thread
Display
Parse error before
Hi, I am migrating the C (messy)programs from HP-UX(cc compiler) to AIX(gcc 3.3.2)
Please help me to resolve this.
Note: Since this is my first post on a forum, so please apologize, if the inputs provided are in not in a good format.The line numbers are mentioned in the sour
You need to take the phrase «parse error before» literally. That implies a C syntax error on your part.
for example, the first refers to this:
Start at the top of the digest and work your way through each error. Sometimes if you click the error in a IDE, the line will be highlighted for you.
Have you actually bothered to look at the code corresponding to the error messages?
For example, line 635 (which triggers the first error) is
That sort of placement of digits, followed the the semi-colon, then a valid token is invalid. Hence the compiler complaining about «parse error before . «.
I haven’t looked further than that, but given that the cause of the first two errors is blindingly obvious, I suggest you apply effort yourself to find the other errors.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
@grumpy I think those digits followed by the semi-colon are for us to find the lines aren’t they?
Anyway he is missing some brackets after the if statement it should be :
I’m on a hurry so couldn’t take the time to look at the full code but maybe the errors are propagating from those missing brackets try to correct and compile again. Hope it helps
P.S: sorry I think whiteflags was faster and better explaining what you should do so follow his tips.
Last edited by beta3designs; 08-19-2011 at 05:30 AM .
Thanks for your precious time to look into this 🙂
And, yes as you mentioned the line numbers like «635:», is just to show you the line numbers.
However, I’ll try to figure it out in the meantime. What I dont understand is, the same code works on HP UX(cc) but not on AIX.
Not to worry. *everything* HP is weird.
If you can, check your HPUX sources; if cc accepts
without parentheses, then you probably let HP know about it.
Most compilers support «extensions», and this is presumably one of them. That generally means some feature that the vendor, or its development team, think is a good thing.
In this case, someone on the HP UX(cc) development team probably had a background in Pascal, or some language derived from Pascal, like Ada.
It is the sort of thing that would be introduced by a programming language zealot/bigot, not through a management decision. A lot of people with a Pascal background think C needs to be improved so it becomes more like Pascal.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Haha. I think either you or they have drastically misunderstood the meaning of the word «improve».
In my opinion, Pascal is a hideously repulsive language whose sole redeeming feature is that it’s not Haskell.
Haha. I think either you or they have drastically misunderstood the meaning of the word «improve».
In my opinion, Pascal is a hideously repulsive language whose sole redeeming feature is that it’s not Haskell.
I didn’t suggest that making C look like Pascal represents an improvement. Some people would though.
Programming language bigotry does not only appear as advocacy of a particular language though, as you have demonstrated.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Bigotry arises from prejudice- i.e. judging things before you really know anything about them. If I started ranting about ALGOL or COBOL, which I’ve never used, because I’d heard other people say they’re useless and outdated you might have a point. My dislike of the two languages I mentioned come from having used them, and I certainly don’t badmouth other languages just because they’re not my first choice. Still have a soft spot for BASIC since that was the language I learnt as a kid (self taught- result was goto-riddled spaghetti code hell until I learned better), and I don’t mind Fortran at all.
I studied Haskell for a semester at university and I didn’t like it because it was slow and full of confusing circumlocutions; although looking back I can see it improved my understanding of C functions, particularly recursion, and also helped me do more with shell scripts.
Pascal annoyed me, firstly because its weird structure isn’t to my taste at all, and secondly because it has this vibe that it’s enforcing someone else’s programming philosophy on me rather than allowing me the freedom to code in my own style. This tends to make me defensive when I hear of Pascal trying to encroach on C’s turf. Another reason I believe C is superior is that C code translated into Pascal tends to still be somewhat elegant, while Pascal translated to C usually isn’t. C has a kind of common sense simplicity and flexibility that other languages don’t, and that’s why I like it.
I don’t think making a judgment on a programming language based on my experiences and impressions of it make me a bigot.
Bigot (n): someone who is intolerant of any differing creed, belief, opinion, or preference.
TheBigH, it is fine, as you have done in your last post, to give a basis for your comments. That way people can decide, for themselves, if your views are relevant to them and their circumstances. Your previous post made blanket statements in an absolute manner, so I interpreted that as bigotry. If you don’t like being described as a bigot, try to remember to provide context when you express judgements.
What annoys you about Pascal is that it is doing exactly what it was designed to do: encouraging specific practices that, when Pascal was designed, were considered best practices for structured programming and data structures. Just because a language isn’t to your taste, doesn’t mean it is horrid for everyone.
Haskell is a functional programming language. Functional programming tends to annoy people who are not used to that paradigm.
There are anti-C bigots who hate exactly the features you love about C: the flexibility that makes it easier to get in trouble, things like pointers that really can really be used to screw things up.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Источник
GCC Debugging/g++/Errors
Contents
abstract declarator ‘TYPE’ used as declaration [ edit | edit source ]
- Message found in GCC version 4.5.1
- often grouped together with:
- member ‘DATA_MEMBER’ with constructor not allowed in anonymous aggregate
- member ‘DATA_MEMBER’ with destructor not allowed in anonymous aggregate
- member ‘DATA_MEMBER’ with copy assignment operator not allowed in anonymous aggregate
- often grouped together with:
- a class or struct is missing a name:
- a header file has a class or struct with a name already used inside ifndef, define statements
call of overloaded ‘FUNCTION’ is ambiguous [ edit | edit source ]
‘VARIABLE’ cannot appear in a constant-expression [ edit | edit source ]
‘VARIABLE’ cannot be used as a function [ edit | edit source ]
- Message found in GCC version 4.5.1
- make sure the variable name does not have an underscore in it (compiler weirdness)
- you’re using the same name for a variable name and a function inside a function definition
conversion from ‘TYPE’ to non-scalar type ‘TYPE’ requested [ edit | edit source ]
- Message found in GCC version 4.5.1
- type conversion error, look for missing «::» syntax or missing parenthesis
- possibly a casting error
- a class member function returns a value that does not match the function’s declared return type
could not convert ‘STATEMENT’ to ‘bool’ [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- you a mistyped comparison operator (e.g., using: «=» instead of «==»)
- you used an incorrect return type for the called function’s definition
- you’re using an invalid argument for a conditional statement
declaration of ‘FUNCTION’ outside of class is not definition [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- try using ‘=’ to initialize a value instead of parenthesis
- you used a semicolon or comma between a constructor and an initializer list instead of a colon
- you left a semicolon before the body of a function definition
declaration of ‘VARIABLE’ shadows a parameter [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- you’re redefining a variable name that’s already in use, possibly declared in the function’s parameter list
‘TYPE’ does not name a type [ edit | edit source ]
- Message found in GCC version 4.5.1
- in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
- in GCC version 4.0.1, sometimes reported as: ISO C++ forbids declaration
- e.g.: ISO C++ forbids declaration of ‘vector’ with no type
- you left out an object’s name qualifier or using directive
- make sure you didn’t mistype the scope operator «::», e.g.: «name:name» instead of «name::name»
- make sure you included the required libraries
- a header file is listed after a file that makes use of it in the include directives
expected ‘TOKEN’ before ‘TOKEN’ token [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
- check for a missing comma or parenthesis in a function’s parameters
- check for a missing semicolon
- e.g.: expected ‘,’ or ‘;’ before ‘TOKEN’
- possibly from a double namespace definition, or a fully-qualified (e.g., std::cout) name already under a ‘using’ directive
- possible missing ‘ >’ operator in a cin/cout statement
expected primary-expression before ‘TOKEN’ [ edit | edit source ]
expected unqualified-id before [ edit | edit source ]
- Message found in GCC version 4.5.1
- check your syntax for missing, misplaced, or erroneous characters
- expected unqualified-id before ‘(‘ token
- e.g.: parentheses in a class name
- expected unqualified-id before ‘return’
- e.g.: missing opening brace in a conditional statement
incompatible types in assignment of ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- Message found in GCC versions 4.5.1
- you’re trying to assign to or initialize a character array using a character pointer
- e.g.: incompatible types in assignment of ‘const char*’ to ‘char [10]’
- improperly accessing elements of a 2D array
invalid conversion from ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- make sure parentheses were not left out of a function name
- make sure you are passing a function the correct arguments
invalid operands of types ‘TYPE’ and ‘TYPE’ to binary ‘FUNCTION’ [ edit | edit source ]
- Message found in GCC version 4.5.1
- You’re trying to concatenate to C string arguments with the addition operator
invalid use of template-name [ edit | edit source ]
is not a member of [ edit | edit source ]
- Message found in GCC versions 4.5.1
- check for a missing header include
example: ‘cout’ is not a member of ‘std’
‘TYPE’ is not a type [ edit | edit source ]
- Message found in GCC version 4.5.1
- in GCC version 3.2.3 reported as: type specifier omitted for parameter ‘PARAMETER’
- you mistyped a template parameter in a function declaration
- an included header file does not have the correct libraries included in the source file to implement it:
- e.g.: you’re using #include «bar.h» without including the «foo.h» that «bar.h» needs to work
- Check that there are no methods with the same name as ‘TYPE’.
‘CLASS_MEMBER’ is private within this context [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- usually reported in the format:
- (LOCATION_OF_PRIVATE_DATA_MEMBER) error: ‘DATA_MEMBER’ is private
- (LOCATION_OF_CODE_ACCESSING_PRIVATE_DATA) error: within this context
- Message usually results from trying to access a private data member of a class or struct outside that class’s or struct’s definition
- Make sure a friend member function name is not misspelled
- make sure a read only function is using a ‘const’ argument type for the class
- make sure functions that alter data members are not const
- check for derived class constructors implicitly accessing private members of base classes
possible fix, assign the whole object rather than part of it:
Источник
Thread: Parse error before
Thread Tools
Search Thread
Display
Parse error before
Hi, I am migrating the C (messy)programs from HP-UX(cc compiler) to AIX(gcc 3.3.2)
Please help me to resolve this.
Note: Since this is my first post on a forum, so please apologize, if the inputs provided are in not in a good format.The line numbers are mentioned in the sour
You need to take the phrase «parse error before» literally. That implies a C syntax error on your part.
for example, the first refers to this:
Start at the top of the digest and work your way through each error. Sometimes if you click the error in a IDE, the line will be highlighted for you.
Have you actually bothered to look at the code corresponding to the error messages?
For example, line 635 (which triggers the first error) is
That sort of placement of digits, followed the the semi-colon, then a valid token is invalid. Hence the compiler complaining about «parse error before . «.
I haven’t looked further than that, but given that the cause of the first two errors is blindingly obvious, I suggest you apply effort yourself to find the other errors.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
@grumpy I think those digits followed by the semi-colon are for us to find the lines aren’t they?
Anyway he is missing some brackets after the if statement it should be :
I’m on a hurry so couldn’t take the time to look at the full code but maybe the errors are propagating from those missing brackets try to correct and compile again. Hope it helps
P.S: sorry I think whiteflags was faster and better explaining what you should do so follow his tips.
Last edited by beta3designs; 08-19-2011 at 05:30 AM .
Thanks for your precious time to look into this 🙂
And, yes as you mentioned the line numbers like «635:», is just to show you the line numbers.
However, I’ll try to figure it out in the meantime. What I dont understand is, the same code works on HP UX(cc) but not on AIX.
Not to worry. *everything* HP is weird.
If you can, check your HPUX sources; if cc accepts
without parentheses, then you probably let HP know about it.
Most compilers support «extensions», and this is presumably one of them. That generally means some feature that the vendor, or its development team, think is a good thing.
In this case, someone on the HP UX(cc) development team probably had a background in Pascal, or some language derived from Pascal, like Ada.
It is the sort of thing that would be introduced by a programming language zealot/bigot, not through a management decision. A lot of people with a Pascal background think C needs to be improved so it becomes more like Pascal.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Haha. I think either you or they have drastically misunderstood the meaning of the word «improve».
In my opinion, Pascal is a hideously repulsive language whose sole redeeming feature is that it’s not Haskell.
Haha. I think either you or they have drastically misunderstood the meaning of the word «improve».
In my opinion, Pascal is a hideously repulsive language whose sole redeeming feature is that it’s not Haskell.
I didn’t suggest that making C look like Pascal represents an improvement. Some people would though.
Programming language bigotry does not only appear as advocacy of a particular language though, as you have demonstrated.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Bigotry arises from prejudice- i.e. judging things before you really know anything about them. If I started ranting about ALGOL or COBOL, which I’ve never used, because I’d heard other people say they’re useless and outdated you might have a point. My dislike of the two languages I mentioned come from having used them, and I certainly don’t badmouth other languages just because they’re not my first choice. Still have a soft spot for BASIC since that was the language I learnt as a kid (self taught- result was goto-riddled spaghetti code hell until I learned better), and I don’t mind Fortran at all.
I studied Haskell for a semester at university and I didn’t like it because it was slow and full of confusing circumlocutions; although looking back I can see it improved my understanding of C functions, particularly recursion, and also helped me do more with shell scripts.
Pascal annoyed me, firstly because its weird structure isn’t to my taste at all, and secondly because it has this vibe that it’s enforcing someone else’s programming philosophy on me rather than allowing me the freedom to code in my own style. This tends to make me defensive when I hear of Pascal trying to encroach on C’s turf. Another reason I believe C is superior is that C code translated into Pascal tends to still be somewhat elegant, while Pascal translated to C usually isn’t. C has a kind of common sense simplicity and flexibility that other languages don’t, and that’s why I like it.
I don’t think making a judgment on a programming language based on my experiences and impressions of it make me a bigot.
Bigot (n): someone who is intolerant of any differing creed, belief, opinion, or preference.
TheBigH, it is fine, as you have done in your last post, to give a basis for your comments. That way people can decide, for themselves, if your views are relevant to them and their circumstances. Your previous post made blanket statements in an absolute manner, so I interpreted that as bigotry. If you don’t like being described as a bigot, try to remember to provide context when you express judgements.
What annoys you about Pascal is that it is doing exactly what it was designed to do: encouraging specific practices that, when Pascal was designed, were considered best practices for structured programming and data structures. Just because a language isn’t to your taste, doesn’t mean it is horrid for everyone.
Haskell is a functional programming language. Functional programming tends to annoy people who are not used to that paradigm.
There are anti-C bigots who hate exactly the features you love about C: the flexibility that makes it easier to get in trouble, things like pointers that really can really be used to screw things up.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
Источник
#include <stdio.h> #include <string.h> int checkVar (char s[3]) { if ((((s[0] <= 90) && (s[0] >= 65)) || ((s[0] >= 97) && ( s[0] <= 122))) && (s[1] == 32)) return 1; printf ("Perem napis ne prav"); return 0; } int chekLeft(char s[3]) { return checkVar(s); } int checkRight ( char s[255]) { int i, j; char s1[3], s2[3], s3[3]; if ((strlen(s) == 9) && (s[2] ==':') && (s[3] == '=') && ((s[6] == '+') || (s[6] == '-') || (s[6] == '*'))) { for (i = 0; i < 2; i++) { s1[i] = s[i]; s2[i] = s[i + 4]; s3[i] = s[i + 7]; s1[3] = ''; s2[3] = ''; s3[3] = ''; } return checkVar(s1)*checkVar(s2)*checkVar(s3); } if ((strlen(s) == 6) && (s[2] ==':') && (s[3] == '=')) { for (i = 0; i < 2; i++) { s1[i] = s[i]; s2[i] = s[i + 4]; s1[3] = ''; s2[3] = ''; } return checkVar(s1)*checkVar(s2); } printf ("oshibka zapisi"); return 0; } int checkAssign (char s[255]) { int i, j; char s1[3]; char s2[255]; for (i = 0; i < strlen(s); i++) { if ((s[i] ==':') && (s[i + 1] == '=')) { strncpy(s1, s, 2); s1[3] = ''; for (j = i + 2; j < strlen(s); j++) s2[j -i - 2] = s[j]; s2[j+1] = ''; return checkLeft(s1)* checkRight(s2); } printf ("Nekorrektna zapis"); return 0; } int checkLinear(char s[255]) { int i, j; for (i = 0; i < strlen(s); i++) if (s[i] == ';') { for (j = 0; j < i; j++) s1[j] = s[j]; s1[j+1] = ''; for (j = i + 2; j < strlen(s); j++) s2[j-i-2] = s[j]; s1[j+1] = ''; return checkAssign(s1)*checkAssign(s2); } return checkAssign(s); } int main () { char s[255]; s[35] = "X :=A ;Y :=X +A ;I :=X -X ;Z :=Z *G "; checkLinear(s); return 0; }
-
Summary
-
Files
-
Reviews
-
Support
-
Wiki
-
Mailing Lists
-
Code
-
Tickets ▾
- Feature Requests
- Bugs
- Patches
-
News
-
Discussion
Menu
▾
▴
parse error
Created:
2004-11-26
Updated:
2012-09-26
-
Hi,
I the following code, i have a parse error, and i don’t unterstand what’s the trouble (adtre a very very long search)
Can somewhere help me before i became crazy ?Thanks in advance
Steph
include <windows.h>
int STDCALL
WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{LPSTR commandLine;
HANDLE hURL_File;
commandLine = lpCmd;hURL_File = CreateFile(«TEST.TXT»,GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hURL_File == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,»Fichier absent»,»Erreur»,MB_OK | MB_ICONHAND);
}
else
{
LPVOID lpBuffer;
DWORD dwBytesRead ;
BOOL bResult ;
DWORD nNOBToRead = 5;ReadFile(hURL_File, lpBuffer, nNOBToRead, dwBytesRead, 0); int iLength ; // parse error before `int' }
}
-
qlmmb2086 should really start a separate thread, or keep quiet until the OP has had his problem sorted, or this will get confusing! You really should not butt in on someone elses thread. There are several ways to get a parse error, and the information you need to post will cause confusion between the two problems.
However, in both cases, you MUST post the complete compile log if you want your question answered. As you can see, the respondants cannot reproduce toy problem, so they need ot see hwat you are seeing. The text you need to copy&paste is in the «Compile Log» tab.
In qlmmb2086’s case, parse errors typically result from missing semi-colons, parentheses, brakets or braces. Because opening and closing braces can be widely spaced, the error may be reported far from the actual error point, so a small code fragment may be insufficient to show the cause — it may not exist in the fragment.
When posting the compile log, the messages indicate the filename and the line number associated with the message. It is useful, especially when posting only a fragment, if you could indicate by an end-line comment in the code which line it refers to.
The requested information will in all probability move you both forward with this problem.
Clifford
-
Doesn’t give me a parse error, instead:
23 C:parse.c [Warning] passing arg 4 of `ReadFile’ makes pointer from integer without a castTry to read Microsoft’s Win32 API documentation how to call the ReadFile function.
-
I’m having a similar problem. I’m just learning C++ for the first time, so I wrote this code while trying to learn switches as a test:
int A;
switch ( A ) {
case 1:
//code
break;
case 2:
//code
break;
…
default:
/code
break;
}For some reason, Dev-C++ keeps returning the error «39 firstccomp.cpp | parse error before `/'» whenever I try to compile. It references the line that says «…» when I do it. Can anyone help?
-
this function is directly from win32.hlp by copy/paste in my code.
if y do this :
// ReadFile(hURL_File, lpBuffer, nNOBToRead, dwBytesRead, 0);
or this
// int iLength ;
i don’t have parse error. It’s very strange.
-
As the warning message says, you have to pass a pointer instead of an integer or DWORD. Something like:
ReadFile(hURL_File, lpBuffer, nNOBToRead, &dwBytesRead, 0);
will let the warning go away. If it doesn’t compile anyway, you should make sure you use the newest version of Bloodshed Dev-C++. It compiles for me.
-
I try that and the result is the same as before :
include <windows.h>
void TestFunction(){}
int STDCALL
WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
TestFunction();
int iLength ; // parse error before `int’
} -
devcpp version 4 build on 21/09/2000 23:22:34
mingW compiler 2.95.2-1 MSVCRT + updated headers and libraries -
it compiles fine here
why are you using that ancient Dev-C++ and compiler?Adrian
-
Hi Adrian,
I try it with devcpp 4.9.9.0, and it compile fine.
However, that is not a very soultion for me, i want to understand what’s wrong with my previous version. In the case i have a similar problem with the latest version of devcpp, i can’t download an update, and i can’t understand why a so simply code do not compile. So much i now, my old version of devcpp is a good tool, and i see no reason of this trouble.
But i thank you all for your help.
-
I tried it with Dev-C++ 4 and it also works
I don’t know what could be wrong in your setupAdrian
-
FYI:
I saw that I was missing a «/» in my last notation after my previous post. I fixed it, but the problem persists.
Log in to post a comment.
Recommended Answers
Your else is outside your while loop .. it might help to format your code more cleanly
while (location != NULL){ if (item == listPtr->item ){ return true; } } // while ends // now we have an else without an if // statement else{ return false; …
Jump to Post
why are you passing an argument of type ifstream to List.insert() when it obviously expects an argument of the type «itemType» ?
I understand you have your items in a file, but do you expect the file to read itself ? You need to write some code to read …
Jump to Post
All 5 Replies
14 Years Ago
Your else is outside your while loop .. it might help to format your code more cleanly
while (location != NULL){
if (item == listPtr->item ){
return true;
}
} // while ends
// now we have an else without an if
// statement
else{
return false;
}
14 Years Ago
Yeah, I realized that. Now I have another issue of more parse errors later in my program. I thought that was causing the rest, like a missing semi-colon or something. But apparently not.
All the errors are happening in the main function at the very end. The first is inside the while statement.
// This is the implementation file for class List
#include <iostream>
#include <fstream>
#include <stddef.h> // to access NULL
#include "List.h"
using namespace std;
typedef NodeType* NodePtr;
struct NodeType
{
ItemType item;
NodePtr next;
};
List::List()
// Post: listPtr is set to NULL.
{
listPtr = NULL;
}
//***********************************************************
List::List(const List& otherList)
// Copy-constructor for List.
{
NodeType* ptr1;
NodeType* ptr2;
if (otherList.listPtr == NULL)
{ listPtr = NULL; }
else
{
listPtr = new NodeType;
listPtr->item = otherList.listPtr->item;
ptr1 = otherList.listPtr->next;
ptr2 = listPtr;
while (ptr1 != NULL)
{ ptr2->next = new NodeType;
ptr2 = ptr2->next;
ptr2->item = ptr1->item;
ptr1 = ptr1->next;
}
ptr2->next = NULL;
}
}
//***********************************************************
bool List::IsThere(ItemType item) const
// Post: If item is in the list IsThere is
// True; False, otherwise.
{
NodeType* location = listPtr;
while (location != NULL)
{ if (item == listPtr->item )
{ return true; } }
return false;
}
//***********************************************************
void List::Insert(ItemType item)
// Pre: item is not already in the list.
// Post: item is the first item in the list.
{
NodeType* location;
if (IsThere(item) == false)
{ location = new NodeType;
location->item = item;
location->next = listPtr;
listPtr = location;
}
}
//***********************************************************
void List::Delete(ItemType item)
// Pre: item is in the list.
// Post: item is no longer in the list.
{
NodeType* location = listPtr;
NodeType* tempLocation;
if (IsThere(item) == true)
{ tempLocation = location->next;
listPtr = listPtr->next;
}
else
{
while (IsThere(item) == true)
{ location = location->next; }
tempLocation = location->next;
location->next = (location->next)->next;
}
delete tempLocation;
}
//***********************************************************
void List::Print() const
// Post: Items on the list are printed on the screen.
{
NodeType* location = listPtr;
while (location != NULL)
{ cout << location->item << endl;
location = location->next; }
}
//***********************************************************
int List::Length() const
// Post: Number of items have been counted; result returned.
{
NodeType* location = listPtr;
int length = 0;
while (location != NULL)
{ location = location->next;
length++; }
return length;
}
//***********************************************************
List::~List()
// Post: All the components are deleted.
{
NodeType* tempPtr;
while (listPtr != NULL)
{
tempPtr = listPtr;
listPtr = listPtr->next;
delete tempPtr;
}
}
int main ()
{
ifstream InData;
InData.open ("int.dat");
while (InData)
{ List.Insert(InData); }
int length = List.Length();
cout << "There are " << length << " many items in this list." << endl;
List.Print();
system ("pause");
return 0;
}
14 Years Ago
why are you passing an argument of type ifstream to List.insert() when it obviously expects an argument of the type «itemType» ?
I understand you have your items in a file, but do you expect the file to read itself ? You need to write some code to read the contents of the file and then pass the correct arguments to the insert function.
14 Years Ago
Okay, that’s how I was told to write that part of the code so that’s what I did. So, how should the code look then? I’m lost.
14 Years Ago
ok I am not sure what your itemType is so lets assume its a basic data type like int or string and your file has those in it.
so
itemType element;
ifstream InData;
InData.open ("int.dat");
if (inData.isopen()){
while (InData >> element){
List.Insert(element);
}
}
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Очень часто начинающие программисты впадают в суеверный ужас, когда видят, что компилятор нашел в тексте программы ошибку, но не понимают, в чем она заключается.
А если помножить этот факт на незнание английского языка («чего там ему не нравится?..») и слабое владение синтаксисом C++ («хм, а может, тут нужна точка с запятой…»), то проблема принимает масштаб катастрофы.
Тот факт, что компилятор в силу своих ограниченных возможностей изо всех сил старается объяснить, что конкретно неверно, не спасает ситуацию. Как быть, если гуглить неохота, а спросить не у кого?
В этом посте на правах копипаста с последующим переводом, дополнениями и исправлениями приведу описание наиболее распространенных сообщений об ошибках и предупреждений компилятора. Неприятность кроется в том факте, что разные компиляторы ругаются на одинаковые ошибки по-разному, а некоторые даже не замечают то, что другие принимают за ошибку. Все зависит от совести разработчиков компилятора, даты его выпуска, и др.
В качестве компилятора возьмем g++, который, в частности, может использоваться в среде Code::Blocks. Версия gcc (куда входит g++) для ОС Windows зовется MinGW. По ходу я буду давать аналоги ошибок из лексикона русскоязычной Microsoft Visual C++.
Итак, частые ошибки:
undeclared identifier
1) Пример
doy.cpp: In function 'int main()':
doy.cpp:25: 'DayOfYear' undeclared (first use this function)
doy.cpp:25: (Each undeclared identifier is reported only once for each function it appears in.)
doy.cpp:25: parse error before ';' token
2) Смысл
Использован идентификатор DayOfYear
, но компилятор не нашел его объявления. Он не знает, что такое DayOfYear
.
3) Когда бывает
- Вы забыли включить какой-то заголовочный файл (
#include...
) - Вы где-то ошиблись в написании идентификатора (при объявлении или использовании)
- Вы вообще забыли, что эту переменную надо объявить
Попытавшись скомпилировать это в Microsoft Visual C++, вы увидите:
error C2065: DayOfYear: необъявленный идентификатор
cout undeclared
1) Пример
xyz.cpp: In function 'int main()':
xyz.cpp:6: 'cout' undeclared (first use this function)
xyz.cpp:6: (Each undeclared identifier is reported only once for each function it appears in.)
2) Смысл
Суперклассика. Без комментариев.
3) Когда бывает
- Вы забыли включить
<iostream>
- Вы забыли написать
using namespace std;
jump to case label
1) Пример
switch.cpp: In function 'int main()':
switch.cpp:14: jump to case label
switch.cpp:11: crosses initialization of 'int y'
2) Смысл
Смысл туманен
3) Когда бывает
Вы попытались объявить и инициализировать переменную (объект, указатель и т.п.) в метке case оператора выбора switch. Правилами C++ это запрещено.
В Microsoft Visual C++ эта ошибка зовется
error C2360: пропуск инициализации 'y' из-за метки 'case'
Выход: заключите операторы этого case’а в фигурные скобки {}.
multi-line string / unterminated string
1) Пример
Программка
#include <iostream>
using namespace std;
int main()
{
cout << "Bob is my buddy;
cout << "and so is Mary" << endl;
}
вызовет бурную реакцию компилятора:
string.cpp:7:12: warning: multi-line string literals are deprecated
string.cpp: In function 'int main()':
string.cpp:7: 'so' undeclared (first use this function)
string.cpp:7: (Each undeclared identifier is reported only once for each function it appears in.)
string.cpp:7: parse error before 'Mary'
string.cpp:8:28: warning: multi-line string literals are deprecated
string.cpp:8:28: missing terminating " character
string.cpp:7:12: possible start of unterminated string literal
2) Смысл
Компилятор думает, что мы хотим создать строковую константу с содержащимся в ней переносом строки, что-то типа
"Hello
world!"
что не поддерживается языком. Также делается предположение о том, что мы, возможно, забыли поставить кавычки в конце первой строки. Собственно, так оно и есть.
3) Когда бывает
Когда не соблюдается правильное количество и положение кавычек в строковых литералах. Надо быть внимательнее.
Microsoft Visual C++ со свойственной ему детской непосредственностью, отметит, что нельзя делать переносы в строках и возмутится, где точка с запятой:
error C2001: newline в константе
error C2146: синтаксическая ошибка: отсутствие ";" перед идентификатором "cout"
comparison between signed and unsigned integer expressions
1) Пример
xyz.cpp: In function 'int main()':
xyz.cpp:54: warning: comparison between signed and unsigned integer expressions
2) Смысл
Это — предупреждение компилятора, которое говорит о том, что мы пытаемся сравнить (==, и т.д.) целочисленное выражение (может принимать положительные, отрицательные значения и 0) и беззнаковое целочисленное выражение (может быть только положительным, либо 0).
3) Когда бывает
Собственно, тогда и бывает. Напомню, что тип int
по умолчанию знаковый, а некоторые функции (например, vector::size()
) возвращают unsigned int
.
К примеру, следующий на первый взгляд безобидный код вызовет описываемое предупреждение:
for (int i = 0; i < grades.size(); i++)
{
// ...
}
Следует помнить, что в памяти знаковые и беззнаковые типы имеют разные внутренние представления, поэтому надо быть чертовски осторожными с указателями.
В Microsoft Visual C++ предупреждение выглядит так:
warning C4018: <: несоответствие типов со знаком и без знака
suggest parentheses around assignment used as truth value
1) Пример
xyz.cpp: In function `int main()':
xyz.cpp:54: warning: suggest parentheses around assignment used as truth value
2) Смысл
Тоже классика. Компилятор предполагает (и в 99% случаев прав), что вы по ошибке включили в скобки в качестве условия для if/while/for вместо условного выражения выражение присваивания.
3) Когда бывает
Чаще всего — в if
‘ах, когда вместо "=="
используется "="
if (length = maxLength)
вместо
if (length == maxLength)
Заминка в том, что это не ошибка, т.к. в скомпилированной программе (если мы проигнорируем предупреждение) выражение присваивания (которое возвращает значение правого аргумента) во всех случаях, кроме тех, когда оно вернет 0
, будет преобразовано к true
.
Ссылки для дальнейшего изучения
Ошибки построения Microsoft Visual C++
GCC Compiler error messages
GCC Warnings
P.S. Следует отметить, что кроме ошибок стадии компиляции встречаются (гораздо реже) ошибки препроцессора (например, если не найден заголовочный файл <iostram>
), ошибки стадии компоновки (можно избежать, если научиться пользоваться средой программирования) и — самый гнусный тип ошибок! — ошибки стадии выполнения. Т.н. runtime error. С ними может справиться только голова программиста, вооруженная отладчиком.