JinTsai
JinTsai

Reputation: 15

the increment of a returned value

I have defined a function like this:

int test(int n) {
    const int b = n;
    return b;
}

While in the main function, I use like this:

 int temp = test(50)++;

And the g++ reports an error:

error: lvalue required as increment operand

Actually, I'm fully confused by this. Would you like to give me some tips or explain it to me.

Upvotes: 0

Views: 158

Answers (4)

CiaPan
CiaPan

Reputation: 9571

'plusplus' operator is (almost) equivalent to '+= 1' that is 'assign the variable its previous value incremented by one'. The value returned is not a variable, so it can not be the left-side argument of an assignment. That's why the increment operator is not applicable here. Just do

t = test(50) + 1;

or

t = test(50);
t ++;

Upvotes: 0

Chetan
Chetan

Reputation: 942

Once constant value get intialised you cant not change that value.So its giving error try to execute same function without increamenting const value.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490018

You can only apply ++ to an lvalue (at least of built-in type). The return value from a function can be an lvalue if if it returns a reference, but otherwise it's an rvalue (in which case, you can't apply ++ to it).

Upvotes: 2

R Sahu
R Sahu

Reputation: 206557

The value returned from test is an rvalue. You cannot use the increment operator (++) on it. You can change your calling code to:

int temp = test(50);
temp++;

or

int temp = test(50) + 1;

Upvotes: 0

Related Questions