Error expected primary expression before else

Fix “Expected Primary-Expression Before” in C++ or Arduino “Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends […]

Содержание

  1. Fix “Expected Primary-Expression Before” in C++ or Arduino
  2. How to fix “Expected Primary-Expression Before” error?
  3. Type 1: Expected primary-expression before ‘>’ token
  4. Type 2: Expected primary expression before ‘)’ token
  5. Type 3: Expected primary-expression before ‘enum’
  6. Type 4: Expected primary expression before ‘.’
  7. Type 5: Expected primary-expression before ‘word’
  8. Type 6: Expected primary-expression before ‘else’
  9. Conclusion
  10. Error expected primary expression before else
  11. Error expected primary expression before else
  12. Error expected primary expression before else
  13. Error expected primary expression before else

Fix “Expected Primary-Expression Before” in C++ or Arduino

“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.

Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.

We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.

Table of Contents

How to fix “Expected Primary-Expression Before” error?

I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.

Type 1: Expected primary-expression before ‘>’ token

This error occurs when when the opening curly brackets ‘<‘ are not properly followed by the closing curly bracket ‘>’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.

Type 2: Expected primary expression before ‘)’ token

Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.

Solution 1:

The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.

Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.

Type 3: Expected primary-expression before ‘enum’

Example 1: All credits to this thread.

Solution 1:

The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:

Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.

Type 4: Expected primary expression before ‘.’

Example 1: All credits go to this thread.

Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.

Type 5: Expected primary-expression before ‘word’

Example 1: All credits go to this thread.

Solution 1:

Here, they are incorrectly using string inside wordLengthFunction().

Fixing it is simple, simply replace

Type 6: Expected primary-expression before ‘else’

Example 1: All credit goes to this thread.

Solution 1:

This code is not correct because after the if statement is closed with ‘>’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘>’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.

Conclusion

And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.

Also, tell me which one of the 6 types were you experiencing in the comments below.

Источник

Error expected primary expression before else

It`s just a part of and text based adventure. xD
A dialogue in it.

Edit: It supposed to work like «Do you want this?» if you say yes, you get it. If no you don`t. If neither you will get question like : «Are you sure?» and it begins in start.

1, you aren’t comparing anything. You’re assigning Answer1 to yes and then assigning Answer1 to Yes.

2, your if statements should be something like

Theres the whole «int main». Now the problem is that before that I put there that «if,if else,else»-thing, when I pressed any key it just went on. Now (after adding that code from int Answer1, etc. to return 18;> it just closes the program, with system(«pause>null») or without.

Because you’re returning something in Main, lol.

when I said to get rid of the ;, I was just saying that because I saw it there.

You can’t return something in main without the program closing.

Well, you never initialized your variables to anything.

So they have random bit patters in them right now, and I doubt those random bit patters match, so your if statement is always returning false causing you to always go to the else.

Источник

Error expected primary expression before else

movie.h
lines 6-7: You don’t need to pass a pointer to movie as an argument. A function that is a member of a class implicity has access to the member variables of the class.

movie.cpp
Line 1,20: Ditto.

Line 13: Simply call enter_movie(). You don’t need to pass any arguments.

Lines 22-27: 1) You don’t need the m-> to call member functions of your class. 2) You don’t specify types in a function call. Types are only specified in a functin prototype. 3) Since you haven’t shown these functions, it’s not clear if these functions are prompting for input. If they are, you don’t need arguments at all.

main.cpp
line 5: 1) You have to pass an integer value, not a type. Again, you don’t specify types in a function call. 2) movie * is a type. You don’t need this argument since the instance of movie is specified by the Movie variable.

You are confusing two concepts:

1. Declaring and defining functions and members of classes.

2. Calling functions and members of classes ( whether you call a class member on an object or a static member on a class)

When you define a function, you have to add the type of the parameter:

Now I want to use the function I wrote:

What you do wrong in the main function:

Is calling the member function with types, instead of values or variables. Try this:

42 in my code is line 1 above.

I took out the pointers and the m->. I took out the parameters of all the function calls with two exceptions. Main line 5 and movie.cpp line 1 have a 0 in them and that’s it. Also in movie.cpp line 20 it’s now just void movie::enter_movie( movie ) . It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors. I tried just declaring the function in the class without any parameters at all since I was asking for the number inside the function but it got mad at me for that too. Feels like c++ is just out to get me. I do things that seem logical to me but the compiler blows up overtime I try something. Anyways, any clues on that last error? 🙂

There are a few problems with the code you posted:
main.cpp
Line 5: There is no reason to dynamically allocate an instance of movie.
Line 6: As I pointed out before, there is no reason to pass a pointer to a movie instance assuming all the OP wants to do is update a single instance (Movie).
Line 7: You have a memory leak. The instance of movie that was dynamically allocated was never released.

@OP

It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors.

In movie.cpp line 1, you’re passing choose as an argument. There is really no need for choose to be an argument since you prompt for it at line 7. However, if you remove choose as an argument, you must declare it locally within menu().

Ok here’s the whole thing, maybe that will clear any confusion of what I’ve attempted to do. Also there’s several blank functions that I just haven’t even gotten to yet because I either don’t know what I’m supposed to use it for or I’m waiting to get past these errors before I get into them. Figured I’d get past the current errors before I start making more. 🙂

output: refers to line 32 in this post.

I’m sorry if the things I’ve done in this code are just ridiculous. I’m amazingly terrible at coding despite spending all of my free time reading the 2 books I have and going to TA office hours. I took me a week just to figure out how to begin designing the thing and it’s been a week of me being stuck at this point. Seems like every thing I do make it worse. I am dying to understand this stuff so any thing you can say to help will be greatly appreciated. Thank you much. 🙂

movie.cpp line 32: get rid of the 0. This function should not have any arguments. 0 is not valid in an argument list.

main.cpp line 19: get rid of this line. There is no reason to dynamically allocate a move instance. It’s also causing a memory leak since you never delete it.

main.cpp line 20: get rid of the 0. You can’t pass a 0 to a function that doesn’t take any arguments.

movie.cpp line 30: If you’re going to pass an argument here, you need to name the argument.

Line 57, 69, 77, 85, 93, 106, 114: Again, if you’re going to pass and argument to these functions, you need to specify a name, not just a type. You can get away with not specifying a name in the declaration, but a name is required in the definition. However, I don’t see that you need any of these arguments.

movie.h line 17: Why is cast a pointer? In movie.cpp line 100, you’re trying to do a getline to a null pointer. That’s going to cause a trap or an exception.

I’m assuming your intention here is to allow multiple cast members. If that’s what you’re trying to do, you should use a vector:

Источник

Error expected primary expression before else

lastNum = userTurn (poisonNum, max, lastNum, midlNum, enteredNum, stepStones* [poisonNum / max] ) ;

is what is giving me the

error. Changing it to

lastNum = userTurn (poisonNum, max, lastNum, midlNum, enteredNum, stepStones* (poisonNum / max) ) ;

I guess this isn’t a variably sized array in that you can’t modify its size once its been declared, but I’ve always wondered why people tell me not to do this. I use this all the time.

My second question is WTF. How in the heck did you manage to declare functions inside main()?

why will the following compile?

It won’t in standards compliant compilers.

Some compilers allow it as an extension, but it’s not legal C++. If you do it, you run the risk of your code not compiling for other people.

Источник

Error expected primary expression before else

totally stuck here. any help is much appreciated.

p.add( «duid» , duid_str(uint16_t *decoded_lcw));

Your syntax here (and all similar lines below it) makes no sense. You are declaring a function prototype in the middle of a function call.

If your intention was to CALL duid_str, the syntax for it is like this:

p.add( «duid» , duid_str(decoded_lcw) );

Notice that you do not redeclare the parameter lists. You simply pass in the value you want to use as the parameter.

error: passing ‘const ldu1’ as ‘this’ argument of ‘virtual uint16_t ldu1::lcf(uint16_t*)’ discards qualifiers

This error is because you have a const member function (snapshot) calling a non-const member function (lcf). This breaks const-correctness.

If lcf does not modify the object’s state. then make it a const function.
Or if it does modify the state, you cannot call it from a const function. and you will have to change ‘snapshot’ to be non-const.

warning: control reaches end of non-void function

This is exactly what it says. You have a function that needs to return a value, but you do not end with a return statement.

You only return values inside of those if() blocks.

If neither of those if blocks execute (ie: if both conditions are false), the function ends without returning anything.

Well you have to return a string. because that’s the function’s return type. The closest thing to «null» for a string would be an empty string.

And yes. you can return that in an else statement. It’s as easy as you think it is:

Источник

  • Forum
  • Beginners
  • Expected primary-expression before «else

Expected primary-expression before «else»

Expected primary-expression before «else»
That is the error I get in both «else» and «else if».
What is wrong in this code.( I searched all around and tried «everything» but found no solution.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int Answer1,Yes,No,yes,no;
  cin >>Answer1;
  if (Answer1=yes)(Answer1=Yes)
  ;
  {
  cout << "nStuff here!n";
  }
  else if (Answer1=no)(Answer1=No)
  ;
  {
  cout << "nMore stuff here!n";
  }
  else
  ;
  {
  cout << "nEven more stuff here!n";
  return 18; //Note:Line 18 is in my original code, line 1 here.
  }

Last edited on

Why are there ;’s after your if statements?

Without those There comes errors: expected `;’ before ‘{‘ token and still the same as before.

Last edited on

What are you trying to compare in your if statement?

It`s just a part of and text based adventure. xD
A dialogue in it.

Edit: It supposed to work like «Do you want this?» if you say yes, you get it. If no you don`t. If neither you will get question like : «Are you sure?» and it begins in start.

Last edited on

Well:

1, you aren’t comparing anything. You’re assigning Answer1 to yes and then assigning Answer1 to Yes.

2, your if statements should be something like

1
2
3
4
5
if (Answer1 == yes || Answer1== Yes)
{
     cout << "stuff here" << endl;
}
else if....etc

Thank you, That worked.

Last edited on

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
int main ()
{
  cout << "Stuff";
  cout << "nnStuffnn";  
  int Name;
  cin >> Name;
  cout << "nStuffn";
  cout << "<Press any key to do stuff.>nn";
  system("pause>null");
  cout << "Stuff.n";
  cout << "Stuff.n";
  int Answer1,Yes,No,yes,no; 
  cin >>Answer1;
  if (Answer1==yes || Answer1==Yes) 
  
  {
  cout << "nStuffn";
  }
  else if (Answer1==no || Answer1==No)
  
  {
  cout << "nStuffn";
  }
  else
  ;
  {
  cout << "nStuffn";
  return 18;
  }
  
  
  
  system("pause>nul");
}

Theres the whole «int main». Now the problem is that before that I put there that «if,if else,else»-thing, when I pressed any key it just went on. Now (after adding that code from int Answer1, etc. to return 18;} it just closes the program, with system(«pause>null») or without.

Last edited on

else
;
{
cout << «nStuffn»;
return 18;
}

Get rid of the ; after the else.

When main returns something (anything) it exits the function, thus closing the program.

Last edited on

Doesn`t help. It still just closes the program.

Because you’re returning something in Main, lol…

when I said to get rid of the ;, I was just saying that because I saw it there.

You can’t return something in main without the program closing.

Oh, sorry about not reading your previous comment with care. Anyways I think the problem is that the line «cin >>Answer1;» isn`t working properly, because I tried it without the «return», and program ignored line «cin >>Answer1;» and just shew me the line «else». I wasn`t able to do the Aswer1, program just skipped it.

Last edited on

Well, you never initialized your variables to anything.

So they have random bit patters in them right now, and I doubt those random bit patters match, so your if statement is always returning false causing you to always go to the else.

Sorry for bothering you so much but how about this.

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
int main ()
{
  cout << "Stuff";
  cout << "nnStuffnn";  
  int Name;
  cin >> Name;
  cout << "nStuffn";
  cout << "<Press any key to do stuff.>nn";
  system("pause>null");
  cout << "Stuff.n";
  cout << "Stuff.n";
  int Answer1,Yes=1,No=2,yes=1,no=2; 
  cin >>Answer1;
  if (Answer1==1)
  
  {
  cout << "nStuffn";
  }
  else if (Answer1==2)
  
  {
  cout << "nStuffn";
  }
  else
  {
  cout << "nStuffn";
  }
  
  
  
  system("pause>nul");
}

What is wrong in this version?

Well, what are you putting into Answer1 when you use cin?

Yes/No/yes/no, however it always gets the «else» statement.(How do I make it work like this)
Now only 1/2 works.

Last edited on

because Yes/No/yes/no are not ints. all your variables are of type int. You should put them as character arrays or strings if you want them to store info like that.

Well thank you for all your help. I think I`ll just use comments like «Press 1 to do that and this, press 2 to do this and that».

Topic archived. No new replies allowed.

unreal

0 / 0 / 1

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

Сообщений: 118

1

13.03.2012, 16:03. Показов 14076. Ответов 15

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


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

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
 int word = 1;
 int d = 0;
 int pr = 0;
 char ch;    
do{
   if(ch == ' ') 
     word++;
     d = word++;
   else
     pr = d/word;
     pr+=pr;
     d==0;   
     }    
    while((ch = getche)!=r);
      cout << "words you use: " << pr << endl;
      system("PAUSE");
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 16:05

2

unreal, у Вас «else» без «if».



0



unreal

0 / 0 / 1

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

Сообщений: 118

13.03.2012, 16:06

 [ТС]

3

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

unreal, у Вас «else» без «if».

как это а что это тогда

C++
1
if(ch == ' ')



0



fasked

Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 16:08

4

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

как это а что это тогда

Это однострочное условие. Тут Вам не python — скобки расставлять надо.

C
1
2
3
4
5
6
7
8
9
10
if(ch == ' ') 
    word++;
 
d = word++;
 
else
    pr = d/word;
 
pr+=pr;
d==0;

Так проблема заметна?



0



unreal

0 / 0 / 1

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

Сообщений: 118

13.03.2012, 16:14

 [ТС]

5

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

Это однострочное условие. Тут Вам не python — скобки расставлять надо.

можете написать код ?

Добавлено через 3 минуты

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

Это однострочное условие. Тут Вам не python — скобки расставлять надо.

C
1
2
3
4
5
6
7
8
9
10
if(ch == ' ') 
    word++;
 
d = word++;
 
else
    pr = d/word;
 
pr+=pr;
d==0;

Так проблема заметна?

ошибка не изменилось(((



0



Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 16:15

6

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

ошибка не изменилось(((

Так и не должна была. Я этот код привел, чтобы показать Вам следующий момент.
Нельзя сделать условие (if-statement), потом выполнить строку кода

вне

условия, а потом поставить else-statement.



0



0 / 0 / 1

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

Сообщений: 118

13.03.2012, 16:17

 [ТС]

7

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

Так и не должна была.

вы помогаете мне или ….)))



0



fasked

Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 16:18

8

Как со стеной, чесслово. Теперь разницу ощущаете?

C++
1
2
3
4
5
6
7
8
if(ch == ' ') {
    word++;
    d = word++;
}
else {
    pr = d/word;
    pr+=pr;
}

И что должно значить это Ваше творение?

C++
1
d == 0;



1



577 / 256 / 18

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

Сообщений: 868

13.03.2012, 16:19

9

опоздал



0



unreal

0 / 0 / 1

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

Сообщений: 118

13.03.2012, 18:50

 [ТС]

10

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

Как со стеной, чесслово. Теперь разницу ощущаете?

C++
1
2
3
4
5
6
7
8
if(ch == ' ') {
    word++;
    d = word++;
}
else {
    pr = d/word;
    pr+=pr;
}

И что должно значить это Ваше творение?

C++
1
d == 0;

это для того чтобы если ch последовательно получал символ то d не дал pr увеличит значение

Добавлено через 20 минут

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

опоздал

нет не опоздал)



0



fasked

Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 18:55

11

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

это для того чтобы если ch последовательно получал символ то d не дал pr увеличит значение

Тогда

C
1
d = 0;

. Один знак «=».



0



unreal

0 / 0 / 1

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

Сообщений: 118

13.03.2012, 19:25

 [ТС]

12

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

Как со стеной, чесслово. Теперь разницу ощущаете?

C++
1
2
3
4
5
6
7
8
if(ch == ' ') {
    word++;
    d = word++;
}
else {
    pr = d/word;
    pr+=pr;
}

И что должно значить это Ваше творение?

C++
1
d == 0;

как исправит эту ошибку 20: invalid conversion from `int (*)()’ to `char’



0



Эксперт С++

5038 / 2617 / 241

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

Сообщений: 4,310

Записей в блоге: 1

13.03.2012, 23:07

13

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

как исправит эту ошибку 20: invalid conversion from `int (*)()’ to `char’

  1. Внимательно прочитать любую книгу из этого списка по основам языка.
  2. Прорешать приведенные в ней задачи.
  3. Ответить самому себе на вопросы:
    • чем указатель на функцию `int (*)()’ отличается от `char’?
    • почему их нельзя привести?
    • как правильно вызывать функции?
  4. Профит.



0



0 / 0 / 1

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

Сообщений: 118

14.03.2012, 00:03

 [ТС]

14

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

  1. Внимательно прочитать любую книгу из этого списка по основам языка.
  2. Прорешать приведенные в ней задачи.
  3. Ответить самому себе на вопросы:
    • чем указатель на функцию `int (*)()’ отличается от `char’?
    • почему их нельзя привести?
    • как правильно вызывать функции?
  4. Профит.

да я знаю int для чисел а char для символов нашёл ошибку забыл ‘ ‘ поставит) спс тебе за всё



0



Эксперт С++

5053 / 3114 / 271

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

Сообщений: 7,045

14.03.2012, 11:00

15

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

int для чисел а char для символов

И то, и то для чисел, по сути. Только вопрос-то совсем другой:

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

чем указатель на функцию `int (*)()’ отличается от `char’?



0



0 / 0 / 1

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

Сообщений: 118

14.03.2012, 14:08

 [ТС]

16

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

И то, и то для чисел, по сути. Только вопрос-то совсем другой:

целое тип



0



03-05-2011


#1

llind212 is offline


Registered User


Error: Expected primary expression before «else»

I am a beginner student learning to use C++ programming. My assignment is to create a program regarding shipping charges. There are three different shipping services (regular, priority, overnight), and four different types of weight with prices. I have the program written out, but when I put it through g++, it says that all of my else statements require primary expressions before them? I am not sure as to what this means. If anyone could look over my coding and point out my errors to me, any input would be greatly appreciated!

Code:

//Lindsay Lewis     March 2011     Project 2_Shipping Charges

#include <iostream>
using namespace std;

int main ()
{

  float weight;

// This step requires the user to input the service code of the package
  char code;
  cout << "Enter R, P, or O for the service code:" << endl;
  cin >> code;

//This step requires the user to input the weight of the package and calculates the shipping charges for Regul
ar, Priority and Overnight shipping service based on the weight of the package.
  switch (code)
  {
    case 'R':
      cout << "The service you chose is Regular service." << endl;
      cout << "Enter the weight of the package:" <<endl;
      cin >> weight;
      cout <<" The weight of your package is" << weight << endl;
      float charger1;
        {
        if (weight <= 2)
          charger1 = weight * 1.00;
          cout << "The shipping charge for this package is" << charger1 << endl;
        }
      float charger2;
        {
        else if (weight > 2 && <= 6)
          charger2 = weight * 1.50;
          cout << "The shipping charge for this package is" << charger2 << endl;
        }
      float charger3;
        {
        else if (weight > 6 && <= 10)
          charger3 = weight * 2.00;
          cout << "The shipping charge for this package is" << charger3 << endl;
        }
      float charger4;
        {
        else
          charger4 = weight * 2.50
          cout << "The shipping charge for this package is" << charger4 << endl;
        }
          break;
   case 'P':
      cout << "The service you chose is Priority service." << endl;
      cout << "Enter the weight of the package:" << endl;
      cin >> weight;
      cout << "The weight of your package is" << weight << endl;
      float chargep1;
        {
        if (weight <= 2)
          chargep1 = weight * 3.50;
          cout << "The shipping charge for this package is:" << chargep1 << endl;
        }
      float chargep2;
        {
        else if (weight >2 && <= 6)
          chargep2 = weight * 5.50;
          cout << "The shipping charge for this package is:" << chargep2 << endl;
        }
      float chargep3;
        {
        else if (weight = >6 && <= 10)
          chargep3 = weight * 7.50;
          cout << "The shipping charge for this pacakge is:" << chargep3 << endl;
        }
      float chargep4;
        {
        else
          chargep4 = weight * 9.50;
          cout << "The shipping charge for this package is:" << chargep4 << endl;
        }
          break;
    case 'O':
      cout << "The service you chose is Overnight service." << endl;
      cout << "Enter the weight of the pacakage:" << endl;
      cin >> weight;
      cout << "The weight of your package is:" << weight << endl;
      float chargeo1;
        {
        if (weight <= 2)
          chargeo1 = weight * 11.50;
          cout << "The shipping charge for this package is:" << chargeo1 << endl;
        }
      float chargeo2;
        {
        else if (weight > 2 && <= 6)
          chargeo2 = weight * 16.50;
          cout << "The shipping charge for this package is:" << chargeo2 << endl;
        }
      float chargeo3;
        {
        else if (weight > 6 && <= 10)
          chargeo3 = weight * 21.50;
          cout << "The shipping charge for this package is:" << chargeo3 << endl;
        }      float chargeo4;
        {
        else
          chargeo4 = weight * 26.50;
          cout << "The shipping charge for this package is:" << chargeo4 << endl;
        }
        break;
    default:
      cout << "Error: Invalid service code." <<endl;
      cout << "Goodbye." << endl;
  }
  return 0;
}


Member Avatar


Sodabread

88



Posting Whiz in Training


13 Years Ago

This is assuming the error is coming from lines 32-37.

Your else statement is inside your if statement’s braces. The error is produced by the IDE thinking there’s no if statement before the else statement. It should look like the following:

if(check){
     // Do something.
}
else{
     // Do something else.
}

Also, an empty else statement serves no purpose that I know of. If you’re not planning on doing any other functionality if the if statement doesn’t execute, you don’t need that else.

Member Avatar

13 Years Ago

Hey, I wrote this code that makes you type two things, then it checks if it is the same. Well, that was it was supposed to do, but then it kept saying:

expected primary-expression before «else»
expected ‘;’ before «else»

Here’s the code

#include <iostream>
#include <time.h>
#include <windows.h>
#include <string.h>
#include <conio.h>

using namespace std;

//global variables
char pass1[1000000] = {0}, pass2[1000000] = {0}, pass3[1000000] = {0};
bool checker=1;
int counter=0, thing=100;
int passCount=0;
int counter1=0;


int main(){
    cout<<"Welcome to the password checker."<<endl;
    cout<<"Please enter your new password."<<endl;
    
    while (true){
       //input
       cin>>pass1;
    
              
       cout<<"Please enter it again."<<endl;      
       
       //enter again, like in those input things   
       cin>>pass2;      
       
       while (counter1<1000000){
          if (!(pass1[passCount]==pass2[passCount])){
             thing=200;
             
          else
             ;
             }
          passCount++;
          counter1++;
       }
          
       if (thing==100)
          cout<<"Okay. Password Saved."<<endl;
          break;
          
       else if (thing==200)
          cout<<"Sorry, your two passwords are different, please type them again."<<endl;
       }

Please tell me what’s wrong.

#include <iostream>
#include <time.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
 
using namespace std;
 
//global variables
char pass1[1000000] = {0}, pass2[1000000] = {0}, pass3[1000000] = {0};
bool checker=1;
int counter=0, thing=100;
int passCount=0;
int counter1=0;
 
 
int main(){
    cout<<"Welcome to the password checker."<<endl;
    cout<<"Please enter your new password."<<endl;
 
    while (true){
       //input
       cin>>pass1;
 
 
       cout<<"Please enter it again."<<endl;      
 
       //enter again, like in those input things   
       cin>>pass2;      
 
       while (counter1<1000000)
       {
          if (!(pass1[passCount]==pass2[passCount]))
          
             thing=200;
 
          else;
             
          passCount++;
          counter1++;
       }
 
       if (thing==100)
          {cout<<"Okay. Password Saved."<<endl;
          break;
}
       else if (thing==200)
          cout<<"Sorry, your two passwords are different, please type them again."<<endl;
       }
       cout<<pass2;
  system("PAUSE");
    return EXIT_SUCCESS;

}

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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error expected primary expression before const
  • Error expect received toequal expected deep equality
  • Error expected primary expression before char
  • Error exp was not declared in this scope
  • Error exiting config vlan mode 40 nv storage failure

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

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