简体   繁体   中英

Ternary operator usage error, “ERROR:void value not ignored as it ought to be”

(choice=='Y'||choice=='y')?((printf("\n...The program is now resetting...\n")&&(main()))):((printf("\n\tThank you for trying out the BPCC App.\n"))&&(exit(0))); 

If I remove the exit(0) the whole program runs correctly but I need to include the exit(0) .

Can you please help me out?

From C11 standard, chapter 6.5.13, Logical AND [ && ] operator

Each of the operands shall have scalar type.

and from the man page of exit()

void exit(int status);

now, the void is not a valid value (or scalar type). So, you cannot write

...:((printf("\n\tThank you for trying out the BPCC App.\n"))&&(exit(0)));
                                                               |--------|
                                        The return value of `exit()` is used
                                            as one of the operands of `&&` here

Hence the error. You cannot write a logic using the return value of exit() (what's the point, basically?). You have to think of something alternative. (like calling exit() as the very next instruction or similar). One possible approach, as metioned in the answer by Mr. @BLUEPIXY , is to make use of comma operator [ , ], as below

.... (printf("\n\tThank you for trying out the BPCC App.\n")) , (exit(0))

That said, the approach (calling main() recursively) is not considered a good practice.

try this

(printf("message") && (exit(0),1))

or

(printf("message") , exit(0))

Function exit is declared the following way

_Noreturn void exit(int status);

So you may not use it in expressions like this

(printf("\n\tThank you for trying out the BPCC App.\n"))&&(exit(0))

Instead of operator && you can use the comma operator.

Thus the ternary operator can look the following way

( choice == 'Y' || choice == 'y' ) 
   ? ( printf( "\n...The program is now resetting...\n" ) , ( void )main() )
   : ( printf( "\n\tThank you for trying out the BPCC App.\n" ), exit( 0 ) ); 

Or the following way

( choice == 'Y' || choice == 'y' ) 
   ? ( printf( "\n...The program is now resetting...\n" ) , exit( main() ) )
   : ( printf( "\n\tThank you for trying out the BPCC App.\n" ), exit( 0 ) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM