I was writing a very simple C/C++ program when I came across rather peculiar behavior.
When calling any two functions in sequence, they run in the order that they are called. For example, if I print out the string "hello" and then the string "world", I expect to get the string "helloworld" printed in the console, and that happens normally as expected.
However, when calling two functions within the call of another function they are executed in reverse order. This is demonstrated in the code below:
#include <iostream>
#include <stdarg.h>
void collector(int n, ...)
{
va_list args;
va_start(args, n);
for (int i = 0; i < n; i++)
{
int elem = va_arg(args, int);
// Do something with the returns
}
va_end(args);
return;
}
int printAndReturn(const char *message)
{
std::cout << message << std::endl;
if (message == "foo")
{
return 1;
}
return 0;
}
int main(void)
{
collector(2, printAndReturn("foo"), printAndReturn("bar"));
printAndReturn("foo");
printAndReturn("bar");
return 0;
}
The expected output of running this simple program is:
foo
bar
foo
bar
Instead, the actual output I see in the console is:
bar
foo
foo
bar
I don't understand why that happens. Is it something to do with the way C/C++ is compiled?
Wether the answer to that is yes or no, can this be fixed without having to reverse the order of the function calls?
Thank you very much in advance for your time and effort. :)