I am a beginner of C++. I am reading a book about C++. I use g++ to compile the following program, which is an example in the book:
/*modified fig1-1.cpp*/
#include <iostream>
using namespace std;
int main()
{
cout << "n Enter an integer";
cin >> (int i);
cout << "n Enter a character";
cin >> (char c);
return 0;
}
Then I get the following error messages:
fig1-2.cpp: In function 'int main()':
fig1-2.cpp:7:10: error: expected primary-expression before 'int'
cin >> (int i);
^
fig1-2.cpp:7:10: error: expected ')' before 'int'
fig1-2.cpp:9:10: error: expected primary-expression before 'char'
cin >> (char c);
^
fig1-2.cpp:9:10: error: expected ')' before 'char'
Could anyone please tell me what happend? Thank you very much in advance.
asked Oct 7, 2016 at 3:48
6
int i
is the syntax for a declaration. It may not appear inside an expression, which should follow cin >>
.
First declare your variable and then use it:
int i;
cin >> i;
The same for char c
:
chat c;
cin >> c;
And I heavily doubt that this is an example in a book teaching C++. It is blatantly wrong syntax. If it really is in the book as a supposedly working example (i.e. not to explain the error), then you should get a different book.
answered Oct 7, 2016 at 3:51
2
you can not use as you are doing you will have to declare i or c first as i have done so
int main()
{
int i;
char c;
cout << "n Enter an integer";
cin >> (i);
cout << "n Enter a character";
cin >> (c);
return 0;
}
answered Oct 7, 2016 at 3:57
1
prutkin41 0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
||||
1 |
||||
20.07.2012, 07:23. Показов 38090. Ответов 7 Метки нет (Все метки)
код
0 |
25 / 25 / 5 Регистрация: 21.04.2011 Сообщений: 141 |
|
20.07.2012, 08:18 |
2 |
Функция how_big_and_litle не возвращает значение, а в заголовке она определена как возвращающая значение. Нужно либо в функцию return 0; поставить либо в определении функции вместо int поставить void
0 |
prutkin41 0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
||||
20.07.2012, 08:29 [ТС] |
3 |
|||
так не работает
0 |
xADMIRALx 69 / 63 / 5 Регистрация: 09.06.2012 Сообщений: 291 |
||||
20.07.2012, 09:10 |
4 |
|||
Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы
0 |
Infinity3000 1066 / 583 / 87 Регистрация: 03.12.2009 Сообщений: 1,255 |
||||
20.07.2012, 09:52 |
5 |
|||
Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы прототип функции не обязательно обьявлять если функция реализованая до первого ее вызова!
1 |
0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
|
20.07.2012, 12:20 [ТС] |
6 |
почему со «smal» компилируется, а с изначальным «small» -нет?
0 |
Schizorb 512 / 464 / 81 Регистрация: 07.04.2012 Сообщений: 869 Записей в блоге: 1 |
||||
20.07.2012, 12:36 |
7 |
|||
prutkin41, не подключай <windows.h>, в нем опеределена
Добавлено через 1 минуту
1 |
0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
|
20.07.2012, 14:04 [ТС] |
8 |
почему возникает переполнение? извиняюсь за нубские вопросы — надо разобраться
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
20.07.2012, 14:04 |
Помогаю со студенческими работами здесь Ошибка «expected primary-expression before ‘>’ token» Перегрузка оператора <<: «expected primary-expression» Исправить ошибку «expected primary-expression» expected primary-expression before «bre» ; expected `;’ before «bre» ; `bre’ undeclared (first use this function) expected primary-expression before «else» В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 8 |
The expected primary expression before occurs due to syntax errors. It usually has a character or a keyword at the end that clarifies the cause. Here you’ll get access to the most common syntax mistakes that throw the same error.
Continue reading to see where you might be getting wrong and how you can solve the issue.
Contents
- Why Does the Expected Primary Expression Before Occur?
- – You Are Specifying the Data Type With Function Argument
- – The Wrong Type of Arguments
- – Issue With the Curly Braces Resulting in Expected Primary Expression Before }
- – The Parenthesis Following the If Statement Don’t Contain an Expression
- How To Fix the Given Error?
- – Remove the Data Type That Precedes the Function Argument
- – Pass the Arguments of the Expected Data Type
- – Ensure The Equal Number of Opening and Closing Curly Brackets
- – Add an Expression in the If Statement Parenthesis
- FAQ
- – What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
- – What Is a Primary Expression in C Language?
- – What Are the Types of Expressions?
- Conclusion
Why Does the Expected Primary Expression Before Occur?
The expected primary expression before error occurs when your code doesn’t follow the correct syntax. The mistakes pointed out below are the ones that often take place when you are new to programming. However, a programmer in hurry might make the same mistakes.
So, here you go:
– You Are Specifying the Data Type With Function Argument
If your function call contains the data type along with the argument, then you’ll get an error.
Here is the problematic function call:
int addFunction(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
int main()
{
int result = addFunction(int 20, int 30);
}
– The Wrong Type of Arguments
Passing the wrong types of arguments can result in the same error. You can not pass a string to a function that accepts an argument of int data type.
int main()
{
int result = addFunction(string “cat”, string “kitten”);
}
– Issue With the Curly Braces Resulting in Expected Primary Expression Before }
Missing a curly bracket or adding an extra curly bracket usually results in the mentioned error.
– The Parenthesis Following the If Statement Don’t Contain an Expression
If the parenthesis in front of the if statement doesn’t contain an expression or the result of an expression, then the code won’t run properly. Consequently, you’ll get the stated error.
How To Fix the Given Error?
You can fix the “expected primary-expression before” error by using the solutions given below:
– Remove the Data Type That Precedes the Function Argument
Remove the data type from the parenthesis while calling a function to solve the error. Here is the correct way to call a function:
int main()
{
int result = addFunction(30, 90);
}
– Pass the Arguments of the Expected Data Type
Double-check the function definition and pass the arguments of the type that matches the data type of the parameters. It will ensure that you pass the correct arguments and kick away the error.
– Ensure The Equal Number of Opening and Closing Curly Brackets
Your program must contain an equal number of opening and closing curly brackets. Begin with carefully observing your code to see where you are doing the mistake.
– Add an Expression in the If Statement Parenthesis
The data inside the parenthesis following the if statement should be either an expression or the result of an expression. Even adding either true or false will solve the issue and eliminate the error.
FAQ
You can view latest topics and suggested topics that’ll help you as a new programmer.
– What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.
– What Is a Primary Expression in C Language?
A primary expression is the basic element of a complex expression. The identifiers, literals, constants, names, etc are considered primary expressions in the C programming language.
– What Are the Types of Expressions?
The different types of expressions include arithmetic, character, and logical or relational expressions. An arithmetic expression returns an arithmetic value. A character expression gives back a character value. Similarly, a logical value will be the output of a logical or relational expression.
Conclusion
The above error revolves around syntax mistakes and can be solved easily with a little code investigation. The noteworthy points depicting the solutions have been written below to help you out in removing the error:
- Never mention the data type of parameters while calling a function
- Ensure that you pass the correct type of arguments to the given function
- You should not miss a curly bracket or add an extra one
- The if statement should always be used with the expressions, expression results, true, or false
The more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
- Forum
- Beginners
- expected primary-expression before «int»
expected primary-expression before «int»
I am a beginner student learning functions. I had an assignment to complete regarding functions and have an error that appears on line 25 stating «expected primary-expression before «int»». When I try to run my program through g++ the program is not displaying the displayMessages. Any input as to how to fix this error would be greatly appreciated!
|
|
Line 25 should be displayMessage(num1, num2);
The type names should only be present when you declare a variable, not when you make a function call.
Last edited on
My program works perfectly! Thank you so much for your help, I really appreciate it!
Topic archived. No new replies allowed.
Your problem is that your are using asterisks («*»)
for(int j=0;j>-1;j++) {
**j= Serial.read(int p1, int p2, int p3);**
}
The asterisk in C/C++ is the pointer operator. You use to get the value pointed by a pointer.
The expression **j
means that j
is a pointer to a pointer that points something. That’s is meaningless here.
Then, the last **
is readed as another pointer to a pointer, and the compiler is expecting a variable or expression that give the value for the pointer, but found «}», which is an error.
You probably tried to comment out that line of code after the compiler barks at the Serial.read()
, which, as Dave X pointed out, is illegal, because Serial.read()
takes no arguments.
And, the syntax function(int x)
is only use for declaring a function, not for calling one.