-1

I came across a different way of returning values and got excited. What does it mean exactly?

If I had to guess, I would say it means something along the line of... if z < 0, then add z and y, else return z?

int ffunction(int x, int y)
{
    int z = x % y;
    return z < 0 ? z + y : z;
}
ricky162
  • 1,231
  • 3
  • 10
  • 10

6 Answers6

4

You're using the ternary operator and returning the result of that. It's basically an if statement on one line. It's saying:

if(z < 0)
{
    return z + y;
}
else
{
    return z;
}
Michael
  • 141
  • 1
  • 9
3

?: is a ternary operator (an operator with three operands) known as the conditional operator. Either the second (z + y) or third operand (z) is executed based on whether the first (z < 0) is true or false. As such,

return z < 0 ? z + y : z;

is equivalent to

if (z < 0) {
   return z + y;
} else {
   return z;
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    it is a conditional operator, but it is not "the conditional operator". It is the ternary operator. – Sixty4Bit Jul 29 '16 at 17:18
  • 2
    @Sixty4Bit, You have it backwards. It is *a* ternary operator known as *the* conditional operator. There are other ternary operators (although not in C). See the linked doc. – ikegami Jul 29 '16 at 17:23
  • Thank you! Learned something today. – Sixty4Bit Jul 29 '16 at 17:24
  • 1
    fyi, ternary simply means it has three operands, just like binary means it has two, and unary means it has only one. Another way of describing operators is where they are placed relative to their operand(s). Prefix operators appear before its operands, postfix after, and infix in the middle. e.g. addition (`a+b`) is a infix binary operator, negation (`-a`) is a prefix unary operator, and postincrement (`a++`) is a postfix unary operator. – ikegami Jul 29 '16 at 17:27
2

Your code in the question is same as:

int ffunction(int x, int y)
{
    int z = x % y;
    if(z < 0){
        return (z + y);
    }

    else{
        return z;
    }
}

In your question a ternary operator is used, which is a form of compact if statement.

VatsalSura
  • 926
  • 1
  • 11
  • 27
2

This is a form of compact if. Basicly, it is saying that:

if ( z < 0 )
    return z + y;
else
    return z;
Amadeus
  • 10,199
  • 3
  • 25
  • 31
1

It means if z is lower than zero ( aka negetive ) return z+y and if this wasn't the case ( z is zero or positive ) return z itself.

It is equivalent to :

if ( z<0)
    return z+y;
else
    return z;
0

Conditional operator. The function returns z+y if the z is smaller than 0, otherwise it returns z.