Search code examples
clogical-and

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?


Solution

  • 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.