0

I am a newbee in C++. Tried the following code:

while((char c = cin.get()) != 'q')
{  //do anything
}

when I try to compile, it fails with following

error: expected primary-expression before "char".

Please help me understand this

Martin York
  • 257,169
  • 86
  • 333
  • 562
bubble
  • 3,408
  • 5
  • 29
  • 51

2 Answers2

2

You cannot have a declaration as a part of an expression.

while ((char c = cin.get()) != 'q') { ...
//      |----------------| <---------------------- this is a declaration
//     |-------------------------| <-------------- this is an expression

You can have a declaration directly inside the parentheses of the loop (not in any nested parentheses):

while (char c = cin.get()) { ...

but this stops on !c, which is not what you want.

This will work:

while (int c = cin.get() - 'q') { // ugly code for illustrative purpose
 c += 'q';
 ...
}

and so will this:

for (char c; (c = cin.get()) != 'q'; ) { // ugly code for illustrative purpose
  ...
}

Update: see also this SO question.

Community
  • 1
  • 1
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

Try this:

char c;
while((c = cin.get()) != 'q')
{  //do anything
}

You are declaring the variable inside parantheses, hence the error:

while (char c = cin.get() != 'q')
  • You may like to try `while(char c = cin.get() != 'q')` – bubble Oct 13 '12 at 09:19
  • @bubble, there are statements and there are expressions. Statements cannot be used as part of expressions. `char c = ...` is a statement. – Don Reba Oct 13 '12 at 09:21
  • yours with "double" bracekts wont work because it does not need the local c variable any more and discards it already only memorizing "true" for the while and this turns ugly for the true != 'q' comparism ;-) – Najzero Oct 13 '12 at 09:21
  • 1
    @ Don Reba they can... if you use a 'if( a = 1 )' (notice the missing second =) it will always do the stuff inside the if and also setting a to 1 – Najzero Oct 13 '12 at 09:24
  • @Najzero I feel `(true != 'q')` is still a valid comparison. It should always return `true`. Isn't it ? – bubble Oct 13 '12 at 09:32
  • hm yep true, my first guess was it casts 'q' to a boolean before comparism... it does not. So hmmm – Najzero Oct 13 '12 at 09:52