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. Показов 38020. Ответов 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 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
In this guide, we’ll explore the common causes and solutions to the «expected primary-expression before int» error in C/C++ programs. This error typically occurs when there is a syntax problem in your code. By following the steps outlined in this guide, you’ll be able to diagnose and fix the issue, ensuring your code runs smoothly.
Table of Contents
- Understanding the Error
- Common Causes and Solutions
- Using Reserved Keywords
- Missing Parentheses or Braces
- Misuse of Semicolons
- Incorrect Function Declaration
- FAQs
- Related Resources
Understanding the Error
Before diving into the solutions, it’s crucial to understand the «expected primary-expression before int» error. This error is generated by the C/C++ compiler when it encounters a syntax problem in your code that prevents it from being parsed correctly.
Here’s a simple example that demonstrates the error:
#include <iostream>
int main() {
int x = 2;
int y = 3;
int result = x + int y;
std::cout << result << std::endl;
return 0;
}
In this code snippet, the compiler will throw the «expected primary-expression before int» error because int y
is not a valid primary expression in C++.
Common Causes and Solutions
Using Reserved Keywords
Problem
One of the most common causes of the error is using C/C++ reserved keywords as variable or function names. This can lead to confusion for the compiler, as it expects these keywords to be used in specific ways.
Solution
Ensure that you’re not using reserved keywords as identifiers in your code. Check the list of C++ reserved keywords and the list of C reserved keywords to make sure you’re not using any of them incorrectly.
Missing Parentheses or Braces
Problem
Another common cause of the «expected primary-expression before int» error is missing or mismatched parentheses or braces. This can lead to the compiler misinterpreting your code.
Solution
Carefully review your code to ensure that all opening and closing parentheses and braces are correctly matched. Consider using an IDE or text editor with syntax highlighting and automatic brace matching to help you catch these errors more easily.
Misuse of Semicolons
Problem
Misusing semicolons can also lead to the «expected primary-expression before int» error. Semicolons are used to separate statements in C/C++, and incorrect placement can cause syntax errors.
Solution
Ensure that you’re using semicolons correctly in your code. Review your code to make sure you’re not accidentally placing a semicolon where it doesn’t belong, such as immediately after a function declaration.
Incorrect Function Declaration
Problem
Incorrect function declaration can also cause the «expected primary-expression before int» error. This often occurs when you’re trying to declare a function with a return type but forget to include the return type in the declaration.
Solution
Review your function declarations to ensure that they include the appropriate return type. For example, if you have a function that returns an integer, make sure to include the int
keyword before the function name in the declaration.
FAQs
1. What does ‘expected primary-expression before int’ mean?
The «expected primary-expression before int» error occurs when the compiler encounters a syntax error in your code, usually related to the use of the int
keyword.
2. How can I prevent this error in the future?
To prevent this error, make sure to:
- Avoid using reserved keywords as identifiers
- Properly match parentheses and braces
- Use semicolons correctly
- Include the correct return type in function declarations
3. Can this error occur in other programming languages?
Yes, similar errors can occur in other programming languages that use similar syntax, such as Java or C#.
4. Which compilers generate this error?
Most C/C++ compilers, including GCC and Clang, can generate the «expected primary-expression before int» error.
5. Can an IDE help me identify and fix this error?
Yes, many IDEs and text editors offer features such as syntax highlighting, automatic brace matching, and error checking, which can help you identify and fix this error more easily.
- C++ Reserved Keywords
- C Reserved Keywords
- GCC Compiler
- Clang Compiler
By understanding the common causes of the «expected primary-expression before int» error and following the solutions outlined in this guide, you’ll be able to quickly diagnose and fix the issue, ensuring your C/C++ code runs smoothly.
- Forum
- Beginners
- expected primary-expression before «int»
expected primary-expression before «int»
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
In this guide, we’ll explore the common causes and solutions to the «expected primary-expression before int» error in C/C++ programs. This error typically occurs when there is a syntax problem in your code. By following the steps outlined in this guide, you’ll be able to diagnose and fix the issue, ensuring your code runs smoothly.
Table of Contents
- Understanding the Error
- Common Causes and Solutions
- Using Reserved Keywords
- Missing Parentheses or Braces
- Misuse of Semicolons
- Incorrect Function Declaration
- FAQs
- Related Resources
Understanding the Error
Before diving into the solutions, it’s crucial to understand the «expected primary-expression before int» error. This error is generated by the C/C++ compiler when it encounters a syntax problem in your code that prevents it from being parsed correctly.
Here’s a simple example that demonstrates the error:
#include <iostream>
int main() {
int x = 2;
int y = 3;
int result = x + int y;
std::cout << result << std::endl;
return 0;
}
In this code snippet, the compiler will throw the «expected primary-expression before int» error because int y
is not a valid primary expression in C++.
Common Causes and Solutions
Using Reserved Keywords
Problem
One of the most common causes of the error is using C/C++ reserved keywords as variable or function names. This can lead to confusion for the compiler, as it expects these keywords to be used in specific ways.
Solution
Ensure that you’re not using reserved keywords as identifiers in your code. Check the list of C++ reserved keywords and the list of C reserved keywords to make sure you’re not using any of them incorrectly.
Missing Parentheses or Braces
Problem
Another common cause of the «expected primary-expression before int» error is missing or mismatched parentheses or braces. This can lead to the compiler misinterpreting your code.
Solution
Carefully review your code to ensure that all opening and closing parentheses and braces are correctly matched. Consider using an IDE or text editor with syntax highlighting and automatic brace matching to help you catch these errors more easily.
Misuse of Semicolons
Problem
Misusing semicolons can also lead to the «expected primary-expression before int» error. Semicolons are used to separate statements in C/C++, and incorrect placement can cause syntax errors.
Solution
Ensure that you’re using semicolons correctly in your code. Review your code to make sure you’re not accidentally placing a semicolon where it doesn’t belong, such as immediately after a function declaration.
Incorrect Function Declaration
Problem
Incorrect function declaration can also cause the «expected primary-expression before int» error. This often occurs when you’re trying to declare a function with a return type but forget to include the return type in the declaration.
Solution
Review your function declarations to ensure that they include the appropriate return type. For example, if you have a function that returns an integer, make sure to include the int
keyword before the function name in the declaration.
FAQs
1. What does ‘expected primary-expression before int’ mean?
The «expected primary-expression before int» error occurs when the compiler encounters a syntax error in your code, usually related to the use of the int
keyword.
2. How can I prevent this error in the future?
To prevent this error, make sure to:
- Avoid using reserved keywords as identifiers
- Properly match parentheses and braces
- Use semicolons correctly
- Include the correct return type in function declarations
3. Can this error occur in other programming languages?
Yes, similar errors can occur in other programming languages that use similar syntax, such as Java or C#.
4. Which compilers generate this error?
Most C/C++ compilers, including GCC and Clang, can generate the «expected primary-expression before int» error.
5. Can an IDE help me identify and fix this error?
Yes, many IDEs and text editors offer features such as syntax highlighting, automatic brace matching, and error checking, which can help you identify and fix this error more easily.
- C++ Reserved Keywords
- C Reserved Keywords
- GCC Compiler
- Clang Compiler
By understanding the common causes of the «expected primary-expression before int» error and following the solutions outlined in this guide, you’ll be able to quickly diagnose and fix the issue, ensuring your C/C++ code runs smoothly.
- 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.