Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Expected expression before ' { ' token"

Tags:

arrays

c

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 code. I have a feeling I am initializing and declaring the array incorrectly and that's why it is giving my issues.

So, before main () I am declaring some group of global variables (yes I know this is dangerous, but required for my purpose). With that group of global variables I also want to declare an double array of size 3

double rob_size, rob_tilt;
double rob_leftcolor [3];
double rob_rightcolor [3];

Then in the main function, I am initializing the variables and arrays

rob_size = 1.0;
rob_tilt = 0.0;
rob_leftcolor [3] = {1.0, 0.0, 0.0}; 
rob_rightcolor [3] = {0.0, 1.0, 0.0};

However, I am getting the error message "Expected expression before ' { ' token" at.

First of all, what does that error message mean? Secondly, is that message coming up because I am initializing and declaring the arrays incorrectly?

Thanks

like image 406
user2930701 Avatar asked Nov 20 '13 03:11

user2930701


2 Answers

Best to do the init'ing at declaration time:

double rob_size = 1.0;
double rob_tilt = 0.0;
double rob_leftcolor [3] = {1.0, 0.0, 0.0}; 
double rob_rightcolor [3] = {0.0, 1.0, 0.0};

Only the arrays need to be done that way, but it's best to do them all the same way.

Your alternative is

rob_leftcolor[0] = 1.0;
rob_leftcolor[1] = 0.0;
rob_leftcolor[2] = 0.0;
like image 152
Charlie Burns Avatar answered Oct 07 '22 02:10

Charlie Burns


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.

like image 31
robertm.tum Avatar answered Oct 07 '22 03:10

robertm.tum