Vipul Sinha
Vipul Sinha

Reputation: 41

Error in compilation. what will be the correct code and output?

why is there a compilation error(lvalue required in line 3)

what will be the correct code and then the output?

 #include<iostream>
 #define PRINT(i,LIMIT) \
  do{   if(i++<LIMIT)\
       { cout<<"Gradeup";\
         continue;  }\
         }\
       while(1)

using namespace std;


int main() {  

PRINT(0,3);
return 0;
}

Upvotes: 0

Views: 85

Answers (2)

doraemon
doraemon

Reputation: 2502

After expanding the macro, if(i++<LIMIT) becomes if (0++ < 3) and 0++ is not an valid expression.

To make it work, you define a variable in your main() and pass that variable to the macro:

int main()
{
    int a = 0;
    PRINT(a, 3);
    return 0;
}

Note, the macro you defined is actually an infinite loop (at least for the parameters given). If you intend to print it for three times, you need

#define PRINT(i, LIMIT) \
do { \
    cout<<"Gradeup";\
}while(++i<LIMIT)

Upvotes: 1

iBug
iBug

Reputation: 37227

Just note that any identifier defined in a macro is not a variable. It's a "replacement identifier". So you don't have a variable named i but anything supplied to there.

Then your macro expands like this

PRINT(0, 3);
// Expand result
do{   if(0++<3)
...

The compiler surely is complaining about that 0++ is not a valid expression. 0 is an Rvalue and thus cannot be used with increment operators (which requires an Lvalue).

Upvotes: 0

Related Questions