I am confuse about the behavior of the following function. Below are some programs on which i stuck:
Case 1:
void f()
{
printf("wow\t");
}
int main()
{
f();
return 0;
}
It gives the output as expected wow.
Case 2:
void f()
{
printf("wow\t");
}
int main()
{
f(f());
return 0;
}
It gives error: invalid use of void expression which is obvious.
Case 3:
int f()
{
printf("wow\t");
}
int main()
{
f(f());
return 0;
}
Why it give the output wow wow?
f() has return type int. But in main it is not stored in any variable. Also f() has not taken any argument but in case 3 it will take argument returned by f().
The same code doesn’t work in C++.
The code
f(f());callsffrom the inner function call and then callsffrom the outer function call. That you don’t store the return value fromfdoesn’t do anything. The compiler can’t avoid calling a function just because you ignore its return value unless it knows the function has no consequences, and this function does have consequences.It’s not unusual at all to ignore the return value of a function. For example, you might have a “remove entries” function that returns the number of entries it removed. You might call that function in a context where you don’t care how many entries it returned, so you ignore the return value. The function still has to run or the entry wouldn’t get removed. Heck, you’re ignoring the return value of
printf. You’d be quite surprised if it didn’t get called though.