Ошибка expected primary expression before int

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

Wei-Cheng Liu's user avatar

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

Sandeep Singh's user avatar

1

prutkin41

0 / 0 / 0

Регистрация: 20.07.2012

Сообщений: 4

1

20.07.2012, 07:23. Показов 38020. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream.h>
using namespace std;
#include <windows.h>
 
int show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
}
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}



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

так не работает

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
   
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
  return(0);
}
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}



0



xADMIRALx

69 / 63 / 5

Регистрация: 09.06.2012

Сообщений: 291

20.07.2012, 09:10

4

Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <stdlib.h> // для system
 
 
using namespace std;
void show_big_and_litle(int a, int b, int c);
 
 
 
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}    
void show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
}



0



Infinity3000

1066 / 583 / 87

Регистрация: 03.12.2009

Сообщений: 1,255

20.07.2012, 09:52

5

Цитата
Сообщение от xADMIRALx
Посмотреть сообщение

Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы

прототип функции не обязательно обьявлять если функция реализованая до первого ее вызова!

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream.h>
using namespace std;
#include <windows.h>
 
void show_big_and_litle(int a, int b, int c)
{
  int smal = a;
  int big = a;
   if(b > big)
   {
    big = b;
   }
  if(b < smal)
    smal = b;
   if(c > big)
    big = c;
   if(c < smal)
    smal = c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<smal<<endl;
 
}
int main()
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
  return 0;
}



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>, в нем опеределена

C++
1
#define small char

Добавлено через 1 минуту
В этой задаче достаточно подключить:
#include <iostream>
#include <cstdlib>



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»
Задача: Задано линейный массив целых чисел. Увеличить на 2 каждый неотъемлемый элемент
массива….

Перегрузка оператора <<: «expected primary-expression»
Здравствуйте, можете пожалуйста подсказать в чём может быть ошибка. уже долго сижу и никак не могу…

Исправить ошибку «expected primary-expression»
Уважаемые форумчане помогите разобраться с простейшей арифметической программой:
#include…

expected primary-expression before «bre» ; expected `;’ before «bre» ; `bre’ undeclared (first use this function)
#include &lt;iostream&gt;
using namespace std;
struct point
{
int x;
int y;
};
int…

expected primary-expression before «else»
я написал эту прог чтобы он считывал слов в приложении.помогите исправит ошибки.если не трудно)…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

How to fix expected primary expression beforeThe 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

What is expected primary expression before errorThe more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

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

Position is Everything

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

void displayMessage (string name, int age);
void displayMessage (int num1, int num2);

int main ()
{
  string name;
  int age;
  cout << "Enter your name:" << endl;
  cin >> name;
  cout << "Enter your age:" << endl;
  cin >> age;

  displayMessage (name, age);

  int num1;
  int num2;
  cout << "Enter an integer:" << endl;
  cin >> num1;
  cout << "Enter another integer:" << endl;
  cin >> num2;

  displayMessage (int num1, int num2);

  return 0;
}

void displayMessage (string name, int age)
{
    cout << "Hello," << name << endl;
    cout << "You are" << age << "years old" << endl;
}

void displayMessage (int num1, int num2)
{
  int sum = num1 + num2;
  int difference = num1 - num2;
  cout << "The sum of the integers is" << sum << endl;
  cout << "The difference of the two integers is" << difference << endl;
}

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.

Возможно, вам также будет интересно:

  • Ошибка expected declaration specifiers or before string constant
  • Ошибка expected declaration before token
  • Ошибка excel введенное значение неверно
  • Ошибка excel runtime error 424
  • Ошибка excel application defined or object defined error 1004

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии