I am learning C and as an exercise, I'm trying to write a simple program without any semicolons. I've had some trouble with replacing return 0
statement but I've found that this is (the only?) way to do it in C: if(exit(0),0){}
.
How exactly does this statement work?
I know that exit()
from stdlib
is a void function but I don't understand what the ,0
part in the if
works (the rest is clear to me).
The ,
operator in C evaluates both its arguments, and returns the value of the second one. So the expression
exit(0), 0
calls exit(0)
and returns 0. So the code you posted is effectively equivalent to:
exit(0);
if (0) {}
However, exit()
should terminate the process, so this should never actually return. The idiom is just being used to prevent spurious compiler warnings.
While learning C, there is no value to figuring out how to write a program without semi-colons. Sounds like you've deviated from learning C into playing with useless tricks.
To answer your question though, when you have multiple statements separated by commas, the "result" is the final statement. if
needs some statement with a value to evaluate, and since exit()
is void it has no value. the 0 following that comma provides a value for if
.
When you writes
int i = (5, 7);
i
assigned 7
not 5
In parenthesis ,
separated expressions executes from LHS to RHS.
Similarly if(exit(0), 0) == if(0)
, but exit(0) executes first. (not optimize to blank)
My following example and its output will help you upto some extent to understand its behavior:
#include<stdio.h>
int fun(char* c){
printf("%s\n", c);
return 0;
}
int main(){
int i = (fun("1"),fun("2"));
if(fun("3"),7){
printf("ONE %d", i);
}
else{
printf("TWO %d", i);
}
}
its Output:
1
2
3
ONE 0
Notice specially last of output ONE
0 printed because in if(fun("3"),7) == if(7)
. Otherwise fun()
returns 0
.
It's just the comma operator.
It means that the right value of the operator is returned, and the left part is evaluated.
In this case it is used so the exit()
can be put in the if
statement, and the 0 is passed as parameter to be checked in the if
statement (it can't work on a void value).
Comma operator may be treated as a give same effect as;
in normal programming. Actually in this case every expression inside if
will be evaluated. But whenever exit()
is called the program will terminate. For details about comma operatorFollow this Link
exit
is a void function and couldn't be used in a if
statement.
However you can mix it with a ,
and then a 0
. The compiler uses 0
as the condition term and you have no syntax error.
In C/C++ a ,
means "Do this and then that" which can wrote in a single statement.