#include <iostream>
using std::cout;
main() {
int value = 2;
int pow = 2;
int res;
cout << value
<< " raised to the power of "
<< pow << ": ";
for(int i = 1, res = 1; i <= pow; ++i) { // ++i or i = i + 1
res = res * value;
}
cout << res;
cout << ", and initial literal constant value: " << value << "\n";
return 0;
}
This is an example from the C++ Primer by Lippman, which is quite outdated ('89) but the second most recommended book to me when I ask about references for learning C++. This is a limbo book until I can get my hands on C++ Programming Language.
Anyway, I changed this code (the original) posted in the book:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <stream.h>
main() {
int value = 2;
int pow = 2;
cout << value
<< " raised to the power of "
<< pow << ": \t";
for(int i = 1, res = 1; i <= pow; ++i) {
res = res * value;
}
cout << res << "\n";
return 0;
}
First off this uses <stream.h> which, with the new g++ compiler is horribly outdated. I found out the hardway. Anyway, this resulted in an error stating the lookup for 'res' was changed for ISO 'for' scoping.
I fixed it by an empty forward declaration of 'res'.
The idea of the program (in the example) is just to output the answer to 2^10 using a control flow statement.
To my dismay and confusion the output of my version (top version) is:
2 raised to the power of 2: 32767, and initial literal constant value: 2
The forward declaration has nothing common with the declaration of variable res in the loop. So they are two different declarations and moreover the res declared in the loop will be deleted after exiting the loop block scope. Also the main shall be declared as int main() One way to correct the program is the following
#include <iostream>
using std::cout;
int main()
{
int value = 2;
int pow = 2;
cout << value
<< " raised to the power of "
<< pow << ": ";
int res = 1;
for ( int i = 0; i < pow; ++i)
{
res *= value;
}
cout << res;
cout << ", and initial literal constant value: " << value << "\n";
return 0;
}
Although it is indeed a highly recommended book, I don't think anyone in 2012 would recommend the 1989 edition, which predates C++ itself by nine years! Consider an upgrade.