Search code examples
c++syntaxg++conditional-operator

Replace if-else with ?: in c++


The original code is:

if (expression1) statement1;
    else statement2;

is it possible to transform it into this?

expression1 ? statement1 : statement2

or it depends on the compiler? it seems that this differs within c++ standards?

Sometimes the case is if (expression1) statement1; and how can i transform that?

btw, it can be done in c.

Making the source code unreadable is exactly what i am trying to do
This is just one of the steps

error: second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
This is what i got with g++ (TDM-2 mingw32) 4.4.1 when compile

#include <stdio.h>

void _(int __, int ___, int ____, int _____)
{
    ((___ / __) <= _____) ? _(__,___+_____,____,_____) : !(___ % __) ?     _(__,___+_____,___ % __, _____) :
    ((___ % __)==(___ / __) && !____) ? (printf("%d\n",(___ / __)),
    _(__,___+_____,____,_____)) : ((___ % __) > _____ && (___ % __) < (___ / __)) ?
    _(__,___+_____,____,_____ + !((___ / __) % (___ % __))) : (___ < __ * __) ?
    _(__,___+_____,____,_____) : 0;
}

int main() {
    _(100,0,0,1);
    return 0;
}

and if i replace the last 0 with throw 0, it will compile successfully.


Solution

  • expression1 ? statement1 : statement2 This is actually incorrect. The correct is this:

    expression1 ? expression2 : expression3

    Not any statement can be equivalently transformed into a single expression, so in general it is not always possible. For example:

    if(expr)
    {
       for(int i = 0; i < 2; ++i) {std::cout << i; }
    }
    else
    { 
       //something else
    }
    

    You can't transform this into ?: expression because for is a statement, not an expression.

    Btw. It can't be done in standard C. What you are referring to is probably the statement expression which is a GCC extension.