I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error: error C2143: syntax error : missing ‘;’ before ‘type’….
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
printf("number is %dn", number++);
}
getch();
}
asked Mar 29, 2013 at 4:10
8
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anything else) must precede all statements within a block.
answered Mar 29, 2013 at 4:17
Ed S.Ed S.
122k22 gold badges182 silver badges263 bronze badges
2
I haven’t used visual in at least 8 years, but it seems that Visual’s limited C compiler support does not allow mixed code and variables. Is the line of the error on the declaration for int i=1;
?? Try moving it above the call to func();
Also, I would use extern void func(void);
answered Mar 29, 2013 at 4:18
Randy HowardRandy Howard
2,18016 silver badges26 bronze badges
this:
int i=1;
for(;i<=5; i++) {
should be idiomatically written as:
for(int i=1; i<=5; i++) {
because there no point to declare for
loop variable in the function scope.
answered Mar 29, 2013 at 4:17
leniklenik
23.2k4 gold badges34 silver badges43 bronze badges
8
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2143 |
Compiler Error C2143 |
11/04/2016 |
C2143 |
C2143 |
1d8d1456-e031-4965-9240-09a6e33ba81c |
Compiler Error C2143
syntax error : missing ‘token1’ before ‘token2’
The compiler expected a specific token (that is, a language element other than white space) and found another token instead.
Check the C++ Language Reference to determine where code is syntactically incorrect. Because the compiler may report this error after it encounters the line that causes the problem, check several lines of code that precede the error.
C2143 can occur in different situations.
It can occur when an operator that can qualify a name (::
, ->
, and .
) must be followed by the keyword template
, as in this example:
class MyClass { template<class Ty, typename PropTy> struct PutFuncType : public Ty::PutFuncType<Ty, PropTy> // error C2143 { }; };
By default, C++ assumes that Ty::PutFuncType
isn’t a template; therefore, the following <
is interpreted as a less-than sign. You must tell the compiler explicitly that PutFuncType
is a template so that it can correctly parse the angle bracket. To correct this error, use the template
keyword on the dependent type’s name, as shown here:
class MyClass { template<class Ty, typename PropTy> struct PutFuncType : public Ty::template PutFuncType<Ty, PropTy> // correct { }; };
C2143 can occur when /clr is used and a using
directive has a syntax error:
// C2143a.cpp // compile with: /clr /c using namespace System.Reflection; // C2143 using namespace System::Reflection;
It can also occur when you are trying to compile a source code file by using CLR syntax without also using /clr:
// C2143b.cpp ref struct A { // C2143 error compile with /clr void Test() {} }; int main() { A a; a.Test(); }
The first non-whitespace character that follows an if
statement must be a left parenthesis. The compiler cannot translate anything else:
// C2143c.cpp int main() { int j = 0; // OK if (j < 25) ; if (j < 25) // C2143 }
C2143 can occur when a closing brace, parenthesis, or semicolon is missing on the line where the error is detected or on one of the lines just above:
// C2143d.cpp // compile with: /c class X { int member1; int member2 // C2143 } x;
Or when there’s an invalid tag in a class declaration:
// C2143e.cpp class X { int member; } x; class + {}; // C2143 + is an invalid tag name class ValidName {}; // OK
Or when a label is not attached to a statement. If you must place a label by itself, for example, at the end of a compound statement, attach it to a null statement:
// C2143f.cpp // compile with: /c void func1() { // OK end1: ; end2: // C2143 }
The error can occur when an unqualified call is made to a type in the C++ Standard Library:
// C2143g.cpp // compile with: /EHsc /c #include <vector> static vector<char> bad; // C2143 static std::vector<char> good; // OK
Or there is a missing typename
keyword:
// C2143h.cpp template <typename T> struct X { struct Y { int i; }; Y memFunc(); }; template <typename T> X<T>::Y X<T>::memFunc() { // C2143 // try the following line instead // typename X<T>::Y X<T>::memFunc() { return Y(); }
Or if you try to define an explicit instantiation:
// C2143i.cpp // compile with: /EHsc /c // template definition template <class T> void PrintType(T i, T j) {} template void PrintType(float i, float j){} // C2143 template void PrintType(float i, float j); // OK
In a C program, variables must be declared at the beginning of the function, and they cannot be declared after the function executes non-declaration instructions.
// C2143j.c int main() { int i = 0; i++; int j = 0; // C2143 }
Нет, не помогает. И если добавить к коду строку int* rowX=*x; вот так:
C | ||
|
, то Ваш код тоже не компилится
Добавлено через 1 минуту
И stdlib.h не помогает
Добавлено через 16 минут
Вот так вроде компилится:
C | ||
|
Но почему не компилился первый вариант, я так и не понял. Только поменял строчки местами, и всё…
Добавлено через 2 минуты
Хотя наверно лучше всё-таки писать float* rowX=(float*)malloc(…) для совместимости с C++
Добавлено через 13 минут
Но когда я продолжил код, начав работать с rowX, снова компилятор стал выёживаться:
C | ||
|
Ошибка 6 error C2143: синтаксическая ошибка: отсутствие «;» перед «тип» d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 7 error C2143: синтаксическая ошибка: отсутствие «;» перед «тип» d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 8 error C2143: синтаксическая ошибка: отсутствие «)» перед «тип» d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 9 error C2143: синтаксическая ошибка: отсутствие «;» перед «тип» d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 10 error C2065: xCnt: необъявленный идентификатор d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 12 error C2065: xCnt: необъявленный идентификатор d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 13 error C2059: синтаксическая ошибка: ) d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 40 1 Vases
Ошибка 14 error C2143: синтаксическая ошибка: отсутствие «;» перед «{» d:documents¦ storeprogrammingvisual studio 2010vasesvasesfilesio.c 41 1 Vases
Добавлено через 11 минут
Даже такой код не компилится
C | ||
|
Ошибка 1 error C2143: синтаксическая ошибка: отсутствие «;» перед «тип» d:documents¦ storeprogrammingvisual studio 2010vasesvasesmain.c 7 1 Vases
Добавлено через 1 час 13 минут
Вот, нашёл в MSDN решение проблемы. Оказывается, микрософтовские разработчики решили спародировать Delphi, цитата:
В программе C переменные необходимо объявлять в начале функции; после того, как функция выполняет не связанные с объявлением инструкции, объявлять переменные нельзя.
C | ||
|
Вот с учётом этого я переписал код так:
C | ||
|
И если переменную цикла объявлять прямо в цикле или присваивать значение rowX после начала других операций, даже не связанных с этой, он будет ругаться. Да, неисповедимы пути микрософта по втыканию палок в колёса труда программистов…
Добавлено через 6 минут
http://msdn.microsoft.com/ru-r… .100).aspx
0
I am new to C++ , I created a Single Document Interface application with MS Visual C++.
when I compile it,some errors have occurred in header file called Day10 SDIDOC.h as follows
error C2143: syntax error : missing ';' before '*'
error C2501: 'CLine' : missing storage-class or type specifiers
error C2501: 'GetLine' : missing storage-class or type specifiers
error C2143: syntax error : missing ';' before '*'
error C2501: 'CLine' : missing storage-class or type specifiers
error C2501: 'AddLine' : missing storage-class or type specifiers
my files are
Day10 SDIDOC.h
public:
CLine * GetLine(int nIndex);
int GetLineCount();
CLine * AddLine(CPoint ptFrom,CPoint ptTo);
CObArray m_oaLines;
virtual ~CDay10SDIDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
these GetLine() and AddLine() methods implement like this in Day10 SDIDOC.cpp
Day10 SDIDOC.cpp
CLine * CDay10SDIDoc::AddLine(CPoint ptFrom, CPoint ptTo)
{
//create a new CLine Object
CLine *pLine = new CLine(ptFrom,ptTo);
try
{
//Add the new line to the object array
m_oaLines.Add(pLine);
//Mark the document as dirty(unsaved)
SetModifiedFlag();
}
//Did we run into a memory exception ?
catch(CMemoryException* perr)
{
//Display a message for the user,giving the bad new
AfxMessageBox("Out of Memory",MB_ICONSTOP|MB_OK);
//Did we create a line object?
if(pLine)
{
//Delete it
delete pLine;
pLine = NULL;
}
//delete the exception object
perr->Delete();
}
return pLine;
}
And GetLine Method
CLine * CDay10SDIDoc::GetLine(int nIndex)
{
return (CLine*) m_oaLines[nIndex];
}
I can’t understand what wrong with.
Please Give me a solution for that.
Thank you…
Почему выдает ошибки?
Ошибки:
Ошибка C2143 синтаксическая ошибка: отсутствие «;» перед «}» 74
Ошибка C2143 синтаксическая ошибка: отсутствие «;» перед «<<» 33
Ошибка C2059 синтаксическая ошибка: } 74
Ошибка C4430 отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию 33
Ошибка C2238 непредвиденные лексемы перед «;» 33
Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31
Сам код:
class bankScore
{
private:
int score = 100,
scoreNum = 945794982938456;
bool setedSum = false,
editedNum = false,
closed = false;
public:
/*void withdraw(int s)
{
if (score - s >= 0)
{
score -= s;
cout << "Деньги успешно сняты";
}
else {
cout << "У вас не хватает денег на счету!";
}
};
void deposit(int s)
{
score -= s;
cout << "Деньги успешно внесены";
};*/
void score()
{
cout << "На вашем счету " << score << " рублей 00 копеек";
};
/*void editScore()
{
if (!editedNum)
{
cout << "Введите новый номер счета (15 цифр): ";
cin >> scoreNum;
cout << "nУспешно!";
editedNum = true;
}
};
void closeScore()
{
if (!closed)
{
cout << "Если вы закроете счет, вы больше не сможете им воспользоваться, а так-же заново открыть его. Вы уверенны?n1. Уверен(-а)n2. Отмена";
int yes = _getch();
switch (yes)
{
case 49:
cout << "Счет закрыт. До свидания!";
case 50:
cout << "Закрытие счета отменено!";
break;
}
closed = true;
}
};
void setScore(int s)
{
if (!setedSum)
{
cout << "Введите сумму: ";
cin >> score;
cout << "nУспешно! Сейчас произведется отчистка" << endl;
_getch();
system("cls");
setedSum = true;
}
};*/
};
-
Вопрос заданболее двух лет назад
-
395 просмотров
Не уверен по поводу чего большинство ошибок, но у тебя определены переменная и функция с одним именем. А так как они располагаются в одной области имен — это проблема. Вот и ругается Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31. Просто прочитай и все.
Пригласить эксперта
-
Показать ещё
Загружается…
09 июн. 2023, в 00:36
1000 руб./за проект
09 июн. 2023, в 00:26
3000 руб./за проект
09 июн. 2023, в 00:03
50000 руб./за проект