Error expected expression before token что это

So I keep on running into this issue when I try assigning values to a int array. I read this one expected expression before '{' token, but I am still confused on why it is showing up in my ...

Q1: What does that error message mean?

A1: The error means that the compiler didn’t expect you to assign an array to a scalar. When you specify rob_leftcolor[3] = {1.0, 0.0, 0.0};, you tell compiler, I want you to assign vector of values {1.0, 0.0, 0.0} to 4th element of array rob_leftcolor (counting starts from 0 — 0, 1, 2, 3). The compiler expects something like rob_leftcolor[0] = 1.0. As you can see, you cannot place 3 elements in the place of one. Also, you tried to assign to the fourth place in the array of three elements.

Q2: Is that message coming up because I am initializing and declaring the arrays incorrectly?

A2: You are declaring the arrays correctly but not assigning them.

Others have correctly told you the preferred way of doing it.

As an alternative, you could also use compound literal operators introduced with the C99 standard.

double rob_size = 1.0;
double rob_tilt = 0.0;
double *rob_leftcolor; 
double *rob_rightcolor;
...
rob_leftcolor = (double []){1.0, 0.0, 0.0};
rob_rightcolor = (double []){0.0, 1.0, 0.0};

Beware, the scope of this array is only inside the function where you assigned it.

Содержание

  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. ошибка: ожидаемое первичное выражение до токена ‘=’ и многие другие
  11. Решение
  12. Другие решения
  13. Error expected expression before token что это

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.

Источник

ошибка: ожидаемое первичное выражение до токена ‘=’ и многие другие

Либо я слепой, либо ошибки нет. Я думаю, что это был бы, вероятно, первый выбор. Пожалуйста, помогите мне найти иголку в стоге сена. Это часть моего списка ошибок:

и это часть моего кода:

У меня есть много подобных ошибок во всем коде, поэтому я думаю, что есть что-то вроде пропуска столбца или чего-то другого. Вы видите это? Я не.

Решение

Макрос не является переменной. Это не имеет значения. Это функция предварительной обработки.

Причина, по которой у вас везде появляются синтаксические ошибки, заключается в том, что ERR_OK и тому подобное были заменены = 0; скорее, чем 0 например.

Другие решения

Другие ответы верны, что проблема заключается в символических константах

Тем не менее, в C ++ есть лучший способ исправить это:

Или C и C ++ оба позволяют

Ваш #define s неверны, они должны выглядеть следующим образом, например:

То есть они не должны иметь = и не заканчивается точкой с запятой. #define это директива препроцессора. Они не подчиняются тем же правилам синтаксиса, что и остальная часть C ++. В частности, директива препроцессора завершается новой строкой, а не точкой с запятой.

Это на самом деле определяет ERR_PARAMS быть = 1; , Если потом заменить ERR_PARAMS с = 1; в своем коде вы увидите, почему всплывают некоторые ошибки. Например, рассмотрим эту строку:

Если вы замените ERR_PARAMS здесь вы получите:

Источник

Error expected expression before token что это

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.

Источник

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
 
#define MAX_SIZE 30
 
typedef struct User_t 
{ 
    char  *login; 
    char  *password; 
    char  *name;
    char  *sex; 
    int    age;
    int    id;  
    float  height; 
    float  weight;
}User;
 
 
/*+*/void clean_memory(User** users, unsigned size)
{
int i;
    for(i=0;i<size;i++)
    {
        free((*users)[size].login);
        free((*users)[size].password);
        free((*users)[size].name);
        free((*users)[size].sex);
    }
free(*users);
*users = NULL;
} 
 
/*+*/void output_f(User** users) 
{ 
int value,n,i;
    printf ("1 - output single data");
    printf ("2 - output all data");
    printf ("select an action : n");
        scanf ("%d",&n);
    switch(n)
    {
        case 1:
            printf ("Input user's id");
                scanf ("%d",value);
            printf ("{id: %d, login: "%s", password: "%s"}n{ name: "%s", sex: "%s", age: %d}n { height:%f, weight:%f}n",
                    (*users)[value].id,(*users)[value].login,(*users)[value].password,(*users)[value].name,(*users)[value].sex,
                (*users)[value].age,(*users)[value].height,(*users)[value].weight);
        break;
        case 2:
            for(i=0;i<value;i++)
                printf("{id: %d, login: "%s", password: "%s"}n{ name: "%s", sex: "%s", age: %d}n { height:%f, weight:%f}n", 
                        (*users)[value].id, (*users)[value].login, (*users)[value].password,(*users)[value].name,(*users)[value].sex,
                        (*users)[value].age,(*users)[value].height,(*users)[value].weight);
        break;
        default :
        break;
    }
}
 
/*+*/void include_f(User** users, unsigned size)  
{
char buffer[128];
bool sex;       
        printf("Input user's loginn");
            scanf("%127s", buffer);
                (users*)[size].login = (char*) malloc(strlen(buffer) + 1); 
                strcpy((users*)[size].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer);
                (users*)[size].password = (char*) malloc(strlen(buffer) + 1); 
                strcpy((users*)[size].password, buffer);  
        printf("Input user's namen");
            scanf("%127s", buffer);
                (users*)[size].name = (char*) malloc(strlen(buffer) + 1);
                strcpy((users*)[size].name, buffer); 
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0: 
        (users*)[size].sex=(char*) malloc(strlen("female")+1);
        strcpy((users*)[size].sex, buffer); 
        break; 
    case 1: 
        (users*)[size].sex=(char*) malloc(strlen("male")+1);
        strcpy((users*)[size].sex, buffer); 
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(users*)[size].age); 
        printf("Input user's heightn"); 
            scanf("%f",(users*)[size].height); 
        printf("Input user's weightn"); 
            scanf("%f",(users*)[size].weight); 
}
 
/*+*/void delete_f(User** users) 
{
int value; 
    printf("Input user's id"); 
        scanf("%d",value); 
    free((*users)[value].login);
    free((*users)[value].password);
    free((*users)[value].name);
    free((*users)[value].sex);
users[value] = NULL;
}
 
void search_f(User** users) 
{
 
}
 
void sort_f(User** users) 
{
int value;
    printf("set the sort task:");
    printf("1 - age n");
    printf("2 - height n");
    printf("3 - weight n");
    printf("4 - sex (male->female) n");
    printf("5 - ABC(A->Z) n");
        scanf("%d",value);
    switch(value)
    {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            break;
        default :
            printf("input right valuen");
            break;  
    }
}
 
/*+*/void edit_f(User** users) 
{
int value;
bool sex;
char buffer[128]; 
    printf ("Input user's id"); 
        scanf ("%d",value); 
        printf ("Input user's loginn");
            scanf("%127s", buffer);
            (users*)[value].login = (char*) malloc(strlen(buffer) + 1); 
            strcpy((users*)[value].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer);
            (users*)[value].password = (char*) malloc(strlen(buffer) + 1);  
            strcpy((users*)[value].password, buffer); 
        printf("Input user's namen");
            scanf("%127s", buffer);
            (users*)[value].name = (char*) malloc(strlen(buffer) + 1);
            strcpy((users*)[value].name, buffer); 
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0:  
        (users*)[value].sex=(char*) malloc(strlen("female")+1);
        strcpy((users*)[value].sex, "female");  
        break; 
    case 1: 
        (users*)[value].sex=(char*) malloc(strlen("male")+1);
        strcpy((users*)[value].sex, "male"); 
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(users*)[value].age); 
        printf("Input user's heightn"); 
            scanf("%f",(users*)[value].height); 
        printf("Input user's weightn"); 
            scanf("%f",(users*)[value].weight); 
}
 
/*+*/void input_f(User** users,unsigned size) 
{ 
unsigned i;
char buffer[128]; 
bool sex;    
    for(i=0;i<size;i++) 
    { 
        (*users)->id=i; 
        printf("Input user's #%dnlogin",i);
            scanf("%127s", buffer);
                (*users)[i].login = (char*) malloc(strlen(buffer) + 1);
                strcpy((*users)[i].login, buffer); 
        printf("Input user's passwordn"); 
            scanf("%127s", buffer); 
                (*users)[i].password = (char*) malloc(strlen(buffer) + 1);  
                strcpy((*users)[i].password, buffer);
        printf("Input user's nnamen");
            scanf("%127s", buffer);
                (*users)[i].name = (char*) malloc(strlen(buffer) + 1);
                strcpy((*users)[i].name, buffer);
        printf("Input user's sex(0-female or 1-male)n"); 
            scanf("%d",sex); 
switch(sex) 
{ 
    case 0: 
        (*users)[i].sex=(char*) malloc(strlen("female")+1);
        strcpy((*users)[i].sex, "female");
        break; 
    case 1: 
        (*users)[i].sex=(char*) malloc(strlen("male")+1);
        strcpy((*users)[i].sex, "male");
        break;
    default:
        break; 
}
        printf("Input user's agen"); 
            scanf("%d",(*users)[i].age); 
        printf("Input user's heightn"); 
            scanf("%f",(*users)[i].height); 
        printf("Input user's weightn"); 
            scanf("%f",(*users)[i].weight); 
    }  
}
 
int main () 
{
User *users = NULL;
unsigned size,value; 
 
bool program=true; 
    printf("Input number of usersn"); 
        scanf("%d",&size);
size = size <= MAX_SIZE? size: MAX_SIZE;
users = (User*) malloc((size+3) * sizeof(User));     
    /*+*/printf("1 - inputn"); 
    /*+*/printf("2 - outputn"); 
    /*+*/printf("3 - include (from the end )n"); 
    /*+*/printf("4 - deleten"); 
    printf("5 - searchn"); 
    printf("6 - sortn");
    /*+*/printf("7 - editn"); 
    /*+*/printf("8 - exitn");  
    while (program) 
    {
        printf("select an action : n");
            scanf("%d", value);
        switch(value) 
        { 
            case 1: 
                input_f(&users,size);  
                break; 
            case 2: 
                output_f(&users);  
                break; 
            case 3:  
                include_f(&users,size);
                size++;  
                break; 
            case 4: 
                delete_f(&users); 
                break; 
            case 5: 
                search_f(&users); 
                break; 
            case 6: 
                sort_f(&users); 
                break;
            case 7: 
                edit_f(&users); 
                break;   
            case 8: 
                program=false; 
                break;
            default:
                printf("input right valuen");
                break;
 
        }   
    }
clean_memory(&users,size);
return 0; 
}



<The previous article in this series | The table of contents of this series | The next article in this series>



The error message seems not correct, and the underlying rule seems not reasonable. . . . Anyway, let me solve the problem.


Topics



About:



C++







The table of contents of this article

  • Starting Context
  • Target Context
  • Orientation
  • Main Body
  • 1: Meeting an «expected primary-expression before ‘>’ token» C++ GCC Compile Error
  • 2: Trying to Solve the Compile Error
  • 3: Solving the Compile Error, and Some Complaints

Starting Context

  • The reader has a basic knowledge on C++.


Target Context

  • The reader will know how to solve an «expected primary-expression before ‘» «>» or whatever «‘ token» C++ GCC compile error.


Orientation

There is an article that clarifies the concept of template in C++.



There is an article that clarifies the distinction between definition and declaration in C++.




Main Body


1: Meeting an «expected primary-expression before ‘>’ token» C++ GCC Compile Error


Hypothesizer 7

«expected primary-expression before ‘>’ token»? What is that supposed to mean? . . .



Well, I am trying to compile this piece of C++ code with GCC (note that I put function template body declarations (which should not be called «definitions») into ‘tpp’ files).



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.hpp




@C++ Source Code

#ifndef __theBiasPlanet_coreUtilitiesTests_templatesTest1_ClassE_hpp__
#define __theBiasPlanet_coreUtilitiesTests_templatesTest1_ClassE_hpp__

namespace theBiasPlanet {
	namespace coreUtilitiesTests {
		namespace templatesTest1 {
			class ClassE {
				public:
				    ClassE ();
				    virtual ~ClassE ();
					template <typename U> U methodE0 (U const & a_argument0) const;
			};
		}
	}
}

#endif



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.cpp




@C++ Source Code

#include "theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.hpp"

namespace theBiasPlanet {
	namespace coreUtilitiesTests {
		namespace templatesTest1 {
			ClassE::ClassE () {
			}
			
			ClassE::~ClassE () {
			}
		}
	}
}



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.tpp




@C++ Source Code

#include "theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.hpp"

namespace theBiasPlanet {
	namespace coreUtilitiesTests {
		namespace templatesTest1 {
			template <typename U> U ClassE::methodE0 (U const & a_argument0) const {
				return a_argument0;
			}
		}
	}
}



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassF.hpp




@C++ Source Code

#ifndef __theBiasPlanet_coreUtilitiesTests_templatesTest1_ClassF_hpp__
#define __theBiasPlanet_coreUtilitiesTests_templatesTest1_ClassF_hpp__
	
	#include "theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassE.hpp"
	
	namespace theBiasPlanet {
		namespace coreUtilitiesTests {
			namespace templatesTest1 {
				class ClassF {
					public:
						template <typename U> static void methodF0 (U const & a_argument0);
						static void methodF1 (ClassE const & a_argument0);
				};
			}
		}
	}
#endif



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassF.cpp




@C++ Source Code

#include "theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassF.hpp"

#include <string>

namespace theBiasPlanet {
	namespace coreUtilitiesTests {
		namespace templatesTest1 {
			void ClassF::methodF1 (ClassE const & a_argument0) {
				a_argument0.methodE0 <std::string> ("aaa");
			}
		}
	}
}



theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassF.tpp




@C++ Source Code

#include "theBiasPlanet/coreUtilitiesTests/templatesTest1/ClassF.hpp"

#include <string>

namespace theBiasPlanet {
	namespace coreUtilitiesTests {
		namespace templatesTest1 {
			template <typename U> void ClassF::methodF0 (U const & a_argument0) {
				a_argument0.methodE0 <std::string> ("aaa");
			}
		}
	}
}



The ‘>’ token mentioned in the message points to the ‘>’ of ‘a_argument0.methodE0 <std::string> («aaa»);’.



In the first place, what, the hell, is «primary-expression»?



This page claims that it means a building block of more complex expressions. . . . I do not know . . .



I do not know because then, I cannot imagine any expression that is not a primary-expression. In fact, what is an expression that cannot be any building block of any more complex expression? . . . For example, an expression, ‘1 + 2’, can be a building block of ‘1 + 2 + 3’; so it should be a primary-expression, although the page does not seem to admit ‘1 + 2’ to be a primary-expression . . .



Anyway, I thank that the page explicitly states that any class name like «MyClass» and «A::B» or any «template id» like «A<int>» is a primary-expression. So, ‘std::string’ is definitely a primary-expression, is it not? . . . The some other documents I have found seem to agree that it is really a primary-expression.



Well, the thing that is before the ‘>’ in my code is . . . «std::string», an assured primary-expression. . . . Mr. compiler, a primary-expression seems to be already there . . .





2: Trying to Solve the Compile Error


Hypothesizer 7

The sloppiness of the message aside, that message was a reminiscent of my past struggle with template.



At that time, I had to put ‘typename’ in order to explicitly teach the compiler that a type name was a type name, which was for assuring that the ‘<‘-‘>’ pair was for template parameterization, not for comparing things.



Well, does the compiler require ‘typename’? How about this?




@C++ Source Code

				a_argument0.methodE0 <typename std::string> ("aaa");"



Nope.



Why? The compiler should now know that the ‘>’ is not any comparison operator, should not?





3: Solving the Compile Error, and Some Complaints


Hypothesizer 7

In fact, there seems to be a rule that any template member on any template-type dependent qualification has to be explicitly declared as a template with ‘.template’.



Well, in my case, ‘methodE0 <U>’ is a template member of ‘a_argument0’, which is a template-type dependent qualification (certainly, it is the qualification and dependent on the template type, ‘U’), so, it has to be ‘a_argument0.template methodE0 <std::string> («aaa»)’.



Hmm . . . , certainly, that has solved the problem, but is such a rule reasonable? . . . I mean, I understand that the rule exists, but I do not understand why the rule is not foolish.



You know, I am not any person that is happy just because a problem has been solved without any satisfactory explanation; I want an explanation why such a rule is necessary.



For example, this (which already exists in the above code) does not cause the error.




@C++ Source Code

			void ClassF::methodF1 (ClassE const & a_argument0) {
				a_argument0.methodE0 <std::string> ("aaa");
			}



That is because, of course, the qualification is independent of any template type, escaping the premise of the rule.



However, I do not see any reason why the flagged line is more a difficulty than the passed line is, for the compiler. . . . You know, the template itself is never compiled, but instantiations of the template are compiled, right? In fact, ‘void ClassF::methodF0 <ClassE> (ClassE const & a_argument0)’ should be no different from ‘void ClassF::methodF1 (ClassE const & a_argument0)’ except the method name.



I understand that a rule that disambiguates ‘<‘ and ‘>’ may be required, but I doubt that the present rule is wisely chosen.



If there is a reasonable necessity for the rule to exist, an understandable explanation would be nice. If the explanation is «You must just obey because I said so!», I would regard such a rule tyrannical, and foolish.






References




<The previous article in this series | The table of contents of this series | The next article in this series>


  1. 09-14-2012


    #1

    m_programmer is offline


    Registered User


    Join Date
    Sep 2012
    Posts
    21

    Post expected expression before ‘)’ token

    hi i am new to c, i keep getting this error. «:32: error: expected expression before ‘)’ token»

    here is my code.

    Code:

    typedef struct{
        char* name;
        int comValue;
    }comName;
    
    
    typedef struct{
        comName* comName;
        struct node *next;
    }node;
    
    
    void insertNode(void){
        node *newNode = (node*)malloc(sizeof(node));
        
        //initialize node
        newNode->next = NULL;
        
    32    newNode->comName= (newNode*)malloc(sizeof(comName));
            
    }

    THANK YOU


  2. 09-14-2012


    #2

    grumpy is offline


    Registered User


    Join Date
    Jun 2005
    Posts
    6,815

    newNode is the name of a variable, not the name of a type. A type conversion as in «(newNode *)» requires the name of a type.

    Unrelated to your problem …. it is a really bad idea, unless you enjoy the prospect of confusing yourself in future, to have variable names the same as type names.

    Also, conversions of the return value from malloc() are not necessary. But you must #include <stdlib.h>

    Right 98% of the time, and don’t care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.


  3. 09-14-2012


    #3

    m_programmer is offline


    Registered User


    Join Date
    Sep 2012
    Posts
    21

    thank you grumpy.
    yes i did include stdlib.h,, i just forgot to paste it in the forum…

    now that i fixed that problem, i keep getting the error, «:32: error: ‘comName’ undeclared (first use in this function)»..!

    thanks


  4. 09-14-2012


    #4

    qny is offline


    Registered User


    Join Date
    Sep 2012
    Posts
    357

    Code:

        newNode->comName= (newNode*)malloc(sizeof(comName));
                                                  ^^^^^^^   <=== THIS comName


  5. 09-14-2012


    #5

    m_programmer is offline


    Registered User


    Join Date
    Sep 2012
    Posts
    21

    haha,, thanks guys… i got confused for a second..! DD


  6. 09-14-2012


    #6

    The Doctor is offline


    Time-Lord Victorious!

    The Doctor's Avatar


    Join Date
    Aug 2012
    Location
    Perth, Western Australia
    Posts
    50

    Quote Originally Posted by qny
    View Post

    Code:

        newNode->comName= (newNode*)malloc(sizeof(comName));
                                                  ^^^^^^^   <=== THIS comName

    And that’s precisely why you don’t have things with the same name ;-D

    I’m new too by the way! I’m enjoying programming in C, but have had a lot of problems.

    Code:

    if (codeWorks( code) && !youCanDoSomethingBetter( code) )
    {
         beHappy();
    } else
    {
         fixCode( code);
    }


  7. 09-14-2012


    #7

    cfanatic is offline


    Registered User


    Join Date
    Jul 2012
    Location
    Australia
    Posts
    242

    Hey, The Doctor, I am also in Perth. Small world.

    And «expected expression before ‘)’ token» is common for me too, as well as ) or ;

    Last edited by cfanatic; 09-14-2012 at 08:05 AM.


See more:

Hi, I gott his error after compiling. I could not find the error, whats the error please?
error:
error: expected expression before ‘{’ token
item[0]={«rice»,10,40,30};

#include<stdio.h>
#include<stdlib.h>
#define ITEMLIMIT 7
#define NOOFITEM  3

struct item_info
{
      char itemname[15];
      int quantity;
      float retail;
      float wholesale;
      //int quatityonorder;
 }item[NOOFITEM];

int main()
{
       item[0]={"rice",10,40,30};
       // item[1]={"sugar",10,40,30};
       // item[2]={"soap",10,40,30};
      int choice = 0,i=0,quantity=0;
      char *itemname;
      printf("item namet quantityt retailspricet wholesaepricet");

     for(i=0;i<NOOFITEM;i++)
          {
          printf("%st %dt %ft %ft",item[i].itemname,item[i].quantity,item[i].retail,item[i].wholesale);
           }

    printf("enter the item which u wantn");
        scanf("%[^n]s",itemname);

     for(i=0;i<NOOFITEM;i++)
        {
            if(strcmp(item[i].itemname,itemname)==0);
      {
                   printf("%s is %d the item in our stock",itemname,i);
        }

        puts("*** checking for item availabiity ****");
        if(item[i].quantity<0)
     {

         puts("item is out of stock");
     }

         else if(item[i].quantity>0)
         {
             printf("quantity of %s avalable is %d",itemname,item[i].quantity);
         }

    printf("enter quatity you want");
    scanf("%d", &quantity);
     if("item[i].quantity>=ITEMLIMIT")
 
<pre lang="cs">printf("your should pay %f as wholesale price",item[i].wholesale*item[i].quantity);
    }

     else if(item[i].quantity< ITEMLIMIT)
    {
           printf("your should pay %f as retail price",item[i].retail*item[i].quantity);
            item[i].quantity=item[i].quantity-quantity;
    }

    printf("enter 2 to coninue");
    scanf("%d",&choice);

    if(choice==1)

<pre lang="cs">break;
    else if(choice==2)
        continue;
}
}


Solution 1

You cannot initialise a structure like that at run time. If you are using constant values then you can get the compiler to set it up by coding:

struct item_info
{
      char itemname[15];
      int quantity;
      float retail;
      float wholesale;
      //int quatityonorder;
}item[NOOFITEM] =
{
    {"rice",10,40,30},
    {"sugar",10,40,30},
    {"soap",10,40,30}
};

But if you want to assign values at run time then you have to do it manually like:

strcpy(item[0].itemname, "rice");
item[0].quantity = 10;
item[0].retail = 40;
item[0].wholesale = 30;

Comments

Solution 3

if you change it so it should compile, but it is not the best way

struct item_info
{
      char *itemname;
      int quantity;
...

You have than the problem that itemname is only a pointer and you need to alloc and free it. And manage it somehow.

I would write an «Setter»

Set(struct *item_info, char*name, ...)
{
 strncpy( item_info->name, sizeof(item_info->name), name);//check length!!!

...
}

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Либо я слепой, либо ошибки нет. Я думаю, что это был бы, вероятно, первый выбор. Пожалуйста, помогите мне найти иголку в стоге сена. Это часть моего списка ошибок:

server.cpp: In function ‘int main(int, char**)’:
server.cpp:64:16: error: expected primary-expression before ‘=’ token
server.cpp:71:14: error: expected primary-expression before ‘=’ token
server.cpp:71:24: error: expected primary-expression before ‘)’ token
server.cpp:71:24: error: expected ‘;’ before ‘)’ token
server.cpp:72:12: error: expected primary-expression before ‘=’ token
server.cpp:80:10: error: expected primary-expression before ‘=’ token
make: *** [server] Error 1

и это часть моего кода:

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <iostream>
#include <regex.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <locale.h>
#include <cstring>
#include <signal.h>
#include <dirent.h>

using namespace std;

/* global variables */
// error codes
#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

// others
#define LISTEN_BACKLOG 50

/* function prototypes */
void printErr(int EC);
int second(int port);

int main(int argc, char **argv)
{
int pflag = 0;
string pvalue;
int port;
int c;

opterr = 0;
while((c = getopt (argc, argv, "p:")) != -1) {
switch(c) {
case 'p':
pflag = 1;
pvalue.assign(optarg);
break;
case '?':
if(optopt == 'c')
fprintf(stderr, "Option -%c requires an argument.n", optopt);
else if(isprint (optopt))
fprintf(stderr, "Unknown option `-%c'.n", optopt);
else
fprintf(stderr, "Unknown option character `\x%x'.n", optopt);
return ERR_PARAMS;
default:
abort();
}
}

if(pflag == 0) {
printErr(ERR_PARAMS);
return ERR_PARAMS;
}
printf ("pvalue = %sn", pvalue.c_str());

port = atoi(pvalue.c_str());

second(port);

return ERR_OK;
}

У меня есть много подобных ошибок во всем коде, поэтому я думаю, что есть что-то вроде пропуска столбца или чего-то другого. Вы видите это? Я не.

-1

Решение

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

должно быть

#define ERR_OK 0
#define ERR_PARAMS 1
#define ERR_SOCKET 2
#define ERR_BIND 3
#define ERR_OTHER 99

Макрос не является переменной. Это не имеет значения. Это функция предварительной обработки.

Причина, по которой у вас везде появляются синтаксические ошибки, заключается в том, что ERR_OK и тому подобное были заменены = 0; скорее, чем 0 например.

4

Другие решения

Другие ответы верны, что проблема заключается в символических константах

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

Тем не менее, в C ++ есть лучший способ исправить это:

const int ERR_OK = 0;
const int ERR_PARAMS = 1;
const int ERR_SOCKET = 2;
const int ERR_BIND = 3;
const int ERR_OTHER = 99;

Или C и C ++ оба позволяют

enum ERROR_CODES {
ERR_OK,
ERR_PARAMS,
ERR_SOCKET,
ERR_BIND,
ERR_OTHER = 99
};

5

Ваш #defines неверны, они должны выглядеть следующим образом, например:

#define ERR_PARAMS 1

То есть они не должны иметь = и не заканчивается точкой с запятой. #define это директива препроцессора. Они не подчиняются тем же правилам синтаксиса, что и остальная часть C ++. В частности, директива препроцессора завершается новой строкой, а не точкой с запятой.

#define ERR_PARAMS = 1;

Это на самом деле определяет ERR_PARAMS быть = 1;, Если потом заменить ERR_PARAMS с = 1; в своем коде вы увидите, почему всплывают некоторые ошибки. Например, рассмотрим эту строку:

printErr(ERR_PARAMS);

Если вы замените ERR_PARAMS здесь вы получите:

printErr(= 1;);

Ну, это, конечно, не правильно!

4

#define ERR_OK = 0;
#define ERR_PARAMS = 1;
#define ERR_SOCKET = 2;
#define ERR_BIND = 3;
#define ERR_OTHER = 99;

должно быть

#define ERR_OK 0
#define ERR_PARAMS 1
#define ERR_SOCKET 2
#define ERR_BIND 3
#define ERR_OTHER 99

1

I’m getting an «: error: expected expression before ‘{’ token»

Discussion in ‘C’ started by billy1, Aug 10, 2007.


  1. billy1

    billy1
    New Member

    Joined:
    Aug 10, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0

    Hi all,
    This is my simple ansi C code:

       int         x, MAT[9]={};
       x = nodeinfo.nodenumber;
       switch(x) {   
            case '0':MAT[] = {1,1,2,1,0,0,0,0};       
                    break;
            case '1':MAT[] = {1,1,2,2,3,1,0,0};
                    break;
            case '2':MAT[] = {1,2,2,1,0,0,0,0};
                    break;
            default:printf("no node availablen");
         }
    

    But I’m getting this compiling error:

    xx.c:12: error: expected expression before ‘{’ token
    xx.c:13: error: expected expression before ‘{’ token

    Can you please let me know what is wrong?

    thanks.

  2. Well, in the first place, it isn’t smaht to show a line number if you don’t show enough code for us to count lines, or at least highlight the line as YOU know it. We’re not sitting in your chair looking at your screen.

    Secondly, the construct, MAT[] = {1,1,2,1,0,0,0,0}; is not a workable runtime operation. It is only good at compile time, when the compiler does you a favor by converting it into an initialization sequence (which becomes a permanent part of the program prior to its conversion to actual executable code).

    In C/C++ arrays are not an atomic thing that can be assigned to in one swell foop. They are a collection of individual items that must be treated individually. Your code is NOT ansi C code, despite your claims to the contrary.

    Last edited: Aug 10, 2007


  3. billy1

    billy1
    New Member

    Joined:
    Aug 10, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0

    Thank you for you quick answer!
    But I still have some questions. Defenitly, I have a conceptual problem which is not described in my books.
    All what I did is in my C books (or at least that’s what I underestand so far..)

    What I wanna do is just a switch or if loop wich -according with a variable I get (x)- then I set some values in an empty defined array.

    1 int x;
    2
    3 x = number; /*here «number» is an int which I get from another function*/
    4
    5 switch(x) {
    6 case 0: int MAT[]={1,2,3,4,5}; /*Initializing the content of an array when it is declared */
    7 break;
    8 case 1: int MAT[]={3,4,5,6,7};
    9 break;
    10 default: printf(«none selectedn»);
    11 }
    Here I’m getting an error in lines 6 and 8 saying:

    error: expected expression before ‘{‘ token
    error: expected expression before ‘{‘ token

    I’ve also tryied setting element by element as you suggested, but I get the same error en each line.

    I tried also using «if-else if» , but the same error message in each line!!

    Thanks for your help!!


  4. billy1

    billy1
    New Member

    Joined:
    Aug 10, 2007
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0

    :confused:

  5. Okay, listen up. You can’t use that type of assignment at run time, only at compile time. The compiler can do that for you, just once, when you compile. The microprocessor cannot do that for you at run time, when it determines what the value of «x» is.

    Let me give you another example. You may put, at the top of your program, a statement like

    char myText [] = "This is my text";
    

    That only works because the compiler writers are doing you a favor. You cannot assign a bunch of characters to an array in C/C++. You have to assign them one at a time. In the foregoing example, the compiler runs all the code necessary to assign the characters, individually. It then stores the result permanently, as a series of characters, in the executable file. When the program is launched that pattern is put into memory BEFORE the executive calls your «main» function. It is then there for your program to work with, as it runs. It is impossible for the compiler to know what «x» is before the program runs. It cannot, therefore, put «This is my text» and «That was my text» in the memory location which has been named «myText».

    I’m sorry if this is confusing to you. You will either have to take my word for it, or think about it, or back your *** off into assembly language and try to put two different values in the same variable at the same time. It ainna gonna woik, Bubba.


  6. Nognir

    Nognir
    New Member

    Joined:
    Jun 27, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0

    Hey guys, I’ve got a similar problem here. I’m trying to make a program to calculate a polyonym but I’m getting an error. Here’s the code:

    #include <stdio.h>
    #include <stdlib.h>
    #define epsilon = 0.0001;
    
    int p_grade, p_2nd, p_1st, p_zero, i, *p;
    float x1,x2,x_0, err, x_mid;
    
    float force (float x, int y)
    {
    	int i, j=1;
    	for (i=1; i < y; i++) j*=x;
    	return j;
    }
    
    float f (int x)			/*Ορισμός συνάρτησης πολυωνύμου*/
    {
    	int i, j=0;
    	for (i=0; i<p_grade; i++)
    	j += p[i]*force(x, p_grade);
    	return j;
    }								/*Τέλος ορισμού*/
    float root (float a, float b)
    {
    	float f1, f_mid, x_mid, err;
    	f1 = f(a);
    	if (f(f1*(f(b)))>0) err = 1.0;
    		else
    			{
    				err = 0;
    				x_mid = (a+b)/2;
    				while (abs(a - x_mid) > epsilon)
    					{
    						f_mid = f(x_mid);
    						if ((f1 * f_mid) <= 0) b = x_mid;
    							else
    							{
    								a = x_mid; f1 = f_mid;
    							}
    						x_mid = (a+b)/2;
    					}
    			}	return x_mid;
    }
    void main()
    {
    	printf("ΒΑΘΜΟΣ ΠΟΛΥΩΝΥΜΟΥ?:");  scanf("%d", &p_grade);	/* Εισαγωγή των δεδομένων της άσκησης*/
    	p = (int *) malloc(p_grade * sizeof (int));
    	if (p == NULL)
    	    {
    	    
    	    }
    	else
    	    {
    	    
    	    }
    	for (i = p_grade; i >= 0; i--) {printf("ΣΥΝΤΕΛΕΣΤΗΣ ΟΡΟΥ i?:"); scanf("%d", &p[i]);}
    
    	printf("Η ΤΙΜΗ Χ1 είναι?:"); 	scanf("%f", &x1);
    	printf("Η ΤΙΜΗ Χ2 είναι?:"); 	scanf("%f", &x2); 	/*Τέλος της εισαγωγής*/
    	free(p);
    }
    

    I get that output:

     gcc -O3 ask3.c
    ask3.c: In function ‘root’:
    ask3.c:31: error: expected expression before ‘=’ token
    ask3.c: In function ‘main’:
    ask3.c:44: warning: return type of ‘main’ is not ‘int’

    Any help here? I’d be grateful


  7. open_mind_core

    open_mind_core
    New Member

    Joined:
    Jun 29, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0

    Your epsilon definition is wrong.

    it should be
    #define epsilon 0.0001,
    not
    #define epsilon = 0.0001;

Share This Page


Go4Expert

Понравилась статья? Поделить с друзьями:
  • Error expected declaration specifiers or before string constant
  • Error expected declaration or statement at end of input перевод
  • Error executing updater binary in zip twrp что делать 4pda
  • Error executing tk17 engine exe
  • Error executing the specified program realtek что делать