Exercise 0-1
What does the following statement do?
3 + 4;
Solution
The statement yields a result of integer (int) type, with the value of 7. As 3 + 4 = 7.
In Detail
- The first operand, 3, is of type integer (int). The result is therefore of type int.
- The addition operator, +, takes in the second operand (4) and add to the first operand (3). The second operand must be of the same (int) type for the addition operator to work.
- The semi-colon at the end discards the result.
- Note that the result is not expected to show in the console output window (e.g. a command window) as it is of type int. Only result of type std::ostream (standard output stream) is displayed in the console output window. For instant, if we submit the following program…
#include <iostream> int main() { 3 + 4; return 0; }
We should expect to see the following output. i.e. the result of 7 does not get output to the console window.
Process returned 0 (0x0) execution time : 0.359 s Press any key to continue.
To get the result to display the int result of 7, we use the std::cout (standard console output) facility, which is of type std::ostream (standard output stream).
#include <iostream> int main() { std::cout << 3 + 4; return 0; }
This now output the result to the console window.
7 Process returned 0 (0x0) execution time : 0.248 s Press any key to continue.
Just a one-line statement and we have covered lots of ground here!
Reference
Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000
For more C++ exercise, please visit : http://ccphplusplus.blogspot.com/