I’ve faced the next one sample:
#include <stdio.h>
// test multiple return
int foo()
{
return 1,2,3,4,5,6;
}
// main entry point
int main(int argc, char* argv[])
{
printf("foo returns: %d\n", foo());
return 0;
}
compile it, then run:
gcc main.cpp -o main
./main
The results are confusing me:
foo returns: 6
The question is: why there is no compile time error?
Because you are using the comma operator: the expression
a,bwhereaandbare arbitrary (usually side-effecting) sub-expressions mean: evaluate the left-hand sideaand discard its result (soais only evaluated for side-effects), then evaluateband give it as result.You cannot return several things from a C function. You should return e.g. an aggregate (usually a
struct) or a dynamically heap-allocated pointer.As to the question, why the compiler don’t say anything? Because you didn’t ask it. You really should compile with
gcc -Wall(for C code) org++ -Wall(for C++ code), and then you get warnings: