Simply stated, why does the following code compile?
#include<iostream>
int foo(){
return 0,1;
}
int main(){
int a,b = foo();
std::cout << a << " " << b << std::endl;
std::cout << foo();
return 0;
}
I am using a 64-bit Window's machine, and compiling with Dev-C++ (using the MinGW GCC 4.5.2 32-bit compiler).
This code prints the following output:
2686824 1
1
I strongly suspect that the value contained in a
is the usual garbage stored in uninitialized variables.
It is clear from this question that returning multiple values from functions is not common practice in industry, and it is definitely discouraged and penalized in programming courses taught at academic institutions.
So why does it work? As I've matured as a programmer, I've realized the incredible value of compiler errors, which are infinitely more intelligible than linker or run-time errors, and obviously way better than bugs.
To be clear, I'm more interested in why this has been allowed from a language design perspective, rather than the technical specifics of how the compiler does its thing (unless, in this case, implementation realities or technical consequences have made it difficult/impossible to detect/manage multiple return
variables).
Are there some esoteric cases where multi-variable return
statments were deemed useful?