IggY
IggY

Reputation: 3135

Same as i++ but for more complex operation

I'm not facing any problem. This question is just about C language

Let's say I have a function like:

int func()
{
    static int i = 1;
    return(i++);
}

Now, instead of doing i++ (i+=1) I'd like to do i *= 42; but still return the value before the multiplication. I'm wondering if there is a way to do it the same way that i++ works (in one expression, take value of i and then do i *= 42).

Upvotes: 0

Views: 70

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263557

Postfix ++ and -- are the only C operators that modify an object and yield that object's previous value. If you want to do that for anything other than incrementing or decrementing by 1, you'll have to store the previous value in a temporary.

If you wanted to design your own language, you could implement a "reverse comma" operator that yields its left operand rather than its right operand. (The existing comma operator evaluates its left operand, then evaluates its right operand, then yields the value of the right operand.)

For example, if the "reverse comma" were spelled ,,, you could do:

return i ,, i *= 42; /* THIS IS NOT C */

Upvotes: 2

An assignment is an expression is C. So you could code

int func() {
 static int i = 1;
 return(i *= 42);
}

Of course if you wanted to return i before multiplying it you need another variable.

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

int func()
{
    static int i = 1;
    int tmp = i;
    i *= 42;
    return tmp;
}

Upvotes: 2

Related Questions