many returns, need one

closed account (j1AR92yv)
int example (int num1)

{

if (num1 > 0)
return num1;

if (num1 < 0 )

return -1*num1;

if (num1 == 0)

return 0;
}

How do make it so where there would be only one return statement?
Last edited on
Use the ternary operator.

condition ? ifTrue : ifFalse;

return (num1 >= 0 ? num1 : -num1);
Or perhaps
1
2
3
4
5
6
7
8
9
int example (int num1)
{
    int result = 0;
    if (num1 > 0)
        result = num1;
    if (num1 < 0 )
        result = -1*num1;
    return result;
}

1
2
3
4
int example (int num1)
{
	return std::abs(num1);
}
The abs() and the ternary are better, but:
1
2
3
4
5
int example( int num1 )
{
    if ( num1 < 0 ) num1 = -num1;
    return num1;
}
Topic archived. No new replies allowed.