Gabriel Marino
Gabriel Marino

Reputation: 23

Ternary with printf and exit function

I want to use a ternary this way

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main (int argc, char **argv) {

   *condition* ? (printf("some text") & exit(1)) : NULL;

   *some code*

   return 0;
};

, but when i compile the file i get this error

36:40: error: void value not ignored as it ought to be
   36 |     condition ? (printf("Some text") & exit(1)) : NULL;
      |                                        ^~~~~~~

i have read some other topics, but i can't find anything enlightening to my situation. i want to if true the condition, to print a message informing that is necessary some arguments to the program to run and then exit because the program don't have the conditions necessary to run.

Upvotes: 0

Views: 237

Answers (1)

KamilCuk
KamilCuk

Reputation: 141688

& is a bitwise AND operation - it takes bits of two operands and computes bitwise AND of them. exit() function returns a void - you can't do calculations on a void value, it's a void.

Typically, comma operator , is used to chain commands in some context where only a single expression is allowed. The type of result of , operator is the type of the second expression.

There are specific rules for allowed types of expressions in conditional operator ?:, and types there can't be void.

The code could be made valid by, for example (assuming condition is valid):

condition ? printf("Some text"), exit(1), 0 : 0;

But really just:

if (condition) { printf("Some text"); exit(1); }

Upvotes: 4

Related Questions