Viodid
Viodid

Reputation: 11

Is it possible to insert an if condition inside a return statement in C?

My purpose is trying to write a function as concise and short as possible.

int func(void)
{
    int a;
    return (
        a = 42,
        a++,
        if (a > 42) a *= -1,
        a);
}

I was expecting to return a -43. Instead I've got a compilation error.

Upvotes: 0

Views: 252

Answers (3)

Madagascar
Madagascar

Reputation: 7345

My purpose is trying to write a function as concise and short as possible.

int a;

return (
   a = 42,
   a++,
   if (a > 42) a *= -1,
   a);

Can simply be rewritten as:

return -43;

Or if that's too short for your liking, then you're looking for the conditional operator (colloquially referred to as the ternary operator), which has the form:

/* if a is logically true (does not evaluate to zero) 
*  then evaluate expression b, otherwise 
*  evaluate expression c
*/
a ? b : c;

So the return statement can be rewritten as:

a = 42;
return ++a > 42 ? -a : a;

As of your objective, then there's no merit to it. You should not write clever code. It harms readability and maintainability. (Although in this case, it doesn't)

Remember:

  1. Simplicity is the ultimate sophistication.Leonardo da Vinci
  2. Any fool can write code that a computer can understand. Good programmers write code that humans can understand.Martin Fowler
  3. Everything should be made as simple as possible — but no simpler.Albert Einstein (attributed).¹

[1] — credit: @SteveSummit

Upvotes: 6

Pengchai
Pengchai

Reputation: 80

If your goal is writing the function don't write it in the main function. write it outside the main and call the function in main The cause of your error is because of your statement expression there is an explanation here https://stackoverflow.com/a/45653540/14308832 So I guess you want to take a as parameter otherwise you can assign a as 42 in func

int func(int a){
    a++;
    return (a > 42 ? a *= -1 : a);
}

int main(void)
{
    printf("%d",func(42));
}

Upvotes: 1

Pepe Segura
Pepe Segura

Reputation: 1

Have you tried this?

int main(void)
{
    int a;

    return (a = 42, a++, a > 42 ? a = a * -1 : a);
}

Upvotes: 0

Related Questions