I have two "equivalent" programs in C and in C++ that have different outputs.
They should print step by step all the powers of a "base" between 0 and "exp"
test.c is:
#include <stdio.h>
int power(int b, int e) {
int p = 1;
for (int i = 0; i < e; i++) {
printf("%d^%d = %d\n", b, i, p);
p = p * b;
}
return p;
}
int main() {
int base = 2, exp = 3;
printf("%d^%d = %d\n", base, exp, power(base, exp));
return 0;
}
output:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
test.cpp is:
#include <iostream>
using namespace std;
int power(int b, int e) {
int p = 1;
for (int i = 0; i < e; i++) {
cout << b << "^" << i << " = " << p << endl;
p = p * b;
}
return p;
}
int main() {
int base = 2, exp = 3;
cout << base << "^" << exp << " = " << power(base, exp) << endl;
return 0;
}
output:
2^3 = 2^0 = 1
2^1 = 2
2^2 = 4
8
Can anybody please tell me why does this happen?
Why does the "cout" print the first part before executing the function?
This is how operator <<
works. First one is evaluated it returns reference to std::cout
then next operator <<
is evaluated and so one. So this C++ code is equivalent to:
int main()
{
int base = 2, exp = 3;
cout << base;
cout << "^";
cout << exp;
cout << " = ";
cout << power(base, exp);
cout << endl;
return 0;
}
So main
prints something before calling power
and prints something after calling power
. Here is some tool which expands C/C++ expressions which shows this to some extent.
In C code all arguments must be evaluated first before main
can print, so power
must finish printing before printing in main
can be done.
Note C++23 has introduced std::print
which is type safe as std::cout
and behaves like printf
in this scenario:
#include <print>
int power(int b, int e)
{
int p = 1;
for (int i = 0; i < e; i++) {
std::print("{}^{} = {}\n", b, i, p);
p = p * b;
}
return p;
}
int main()
{
int base = 2, exp = 3;
std::print("{}^{} = {}\n", base, exp, power(base, exp));
return 0;
}