Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you subtract from a negative integer but add to a positive?

Simple question really, although I'm not sure if there's an answer. I am handling an integer which can be positive or negative.

However, I would like to either increment or decrement it dependant on the sign.

For example, if it's "2", then add 1 and make it "3".

If it's "-2", then subtract 1 and make it "-3".

I already know the obvious method to fix this by adding if statements and having two separate increment and decrement sections. But, I'm trying to limit the amount of code I use and would like to know if there's a similar way of doing this from a built-in function or procedure.

like image 682
Shivam Malhotra Avatar asked Dec 02 '22 22:12

Shivam Malhotra


1 Answers

Try it:

int IncOrDec(int arg)
{
    return arg >= 0 ? ++arg : --arg;
}
like image 50
DreamChild Avatar answered Jan 31 '23 00:01

DreamChild