One-liner if statements, how to convert this if-else-statement

后端 未结 4 1978
温柔的废话
温柔的废话 2020-12-09 14:30

Total noob here so be gentle. I\'ve looked everywhere and can\'t seem to find the answer to this. How do I condense the following?

if (expression)
{
    re         


        
相关标签:
4条回答
  • 2020-12-09 15:12

    Since expression is boolean:

    return expression;
    
    0 讨论(0)
  • 2020-12-09 15:16

    All you'd need in your case is:

    return expression;
    

    The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

    0 讨论(0)
  • 2020-12-09 15:22

    If expression returns a boolean, you can just return the result of it.

    Example

     return (a > b)
    
    0 讨论(0)
  • 2020-12-09 15:33
    return (expression) ? value1 : value2;
    

    If value1 and value2 are actually true and false like in your example, you may as well just

    return expression;
    
    0 讨论(0)
提交回复
热议问题