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 = %dn", b, i, p);
p = p * b;
}
return p;
}
int main() {
int base = 2, exp = 3;
printf("%d^%d = %dn", 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?
Francesco Antropoli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
cout
is evaluated left-to-right. It simply prints everything it sees, when it sees it. So, in your case, your function is called only after printing the first part of the line.
printf
, on the other hand, needs to evaluate everything to fill itself in. So, it runs your function first and then prints.
If you want to get this behavior in C++, it probably makes the most sense to define your output as a string, fill in your output, and then print that all at once, such as:
#include <iostream>
#include <sstream>
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() {
stringstream out;
int base = 2, exp = 3;
out << base << "^" << exp << " = " << power(base, exp);
cout << out.str() << endl;
return 0;
}
This code has the exact same output as your C code.
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;
}
https://godbolt.org/z/vEeMP5nbP