Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: expected primary-expression before ‘=’ token when using for loops [duplicate]

Tags:

c++

Possible Duplicate:
lvalue required as left operand of assignment
lvalue required as left operand of assignment (C program)

I am getting this error on my code and I am not sure why. Please help! The error is:

error: expected primary-expression before ‘=’ token

This is the part of my code i'm having the issue with. a and b were already previously declared as ints.

   int i = 0;
   for( i == a; i < = b; i = i + 1)  // ERROR IS IN THIS LINE
   {  int j = 1;
      int N = static_cast<int>(sqrt(i));

      for( j = 1; j < = N; j = j + 1)   // ERROR IS IN THIS LINE
      {  int P = i%j;
         if( P == 0 && j!= 1 && j!= i)
         {  j = N + 1;
         }
         if( P != 0 && j == N)
         {  cout << i << "is prime" << endl;
         }                                         
      }
   }                                                     
like image 602
user1757575 Avatar asked Apr 20 '26 14:04

user1757575


2 Answers

I think you meant to do

if( P != 0 && j == sqrt(i))

= is the assignment operator, == tests for equivalence and returns boolean.

The assignment operator has lesser precedence than logical AND (&&), so it being read as

(P != 0 && j) = sqrt(i)

which is why the lvalue error is being reported.

like image 195
Anirudh Ramanathan Avatar answered Apr 22 '26 03:04

Anirudh Ramanathan


I'll play along. The 'error' is the same in both case:

for( i == a; i < = b; i = i + 1)  // ERROR IS IN THIS LINE
...
for( j = 1; j < = N; j = j + 1)   // ERROR IS IN THIS LINE

The error is the '< =' which is not an operator and not valid C or C++. Sidenote, the 'i == a' in the first loop is a no-op.

like image 24
Nik Bougalis Avatar answered Apr 22 '26 03:04

Nik Bougalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!