Skip to main content

2.9) Exercise 4


Open the provided file ex4.cpp in your text editor and study it. Then try compiling it with each of the commands below. In each case, it should compile successfully - but what warnings (if any) do you see?

g++ ex4.cpp -o ex4
g++ -Wall ex4.cpp -o ex4
g++ -Wall -Wconversion ex4.cpp -o ex4

Try running the program. Can you explain the output that you see?

If you find the value displayed for variable s confusing, edit the program and change the assigned value from 80000 to 32767 (the maximum representable value for the short type). Recompile and rerun the program. Then change the value to 32768, recompile and rerun. What you are seeing here is integer overflow, a source of potentially serious bugs in programs written in C, C++ and some other languages.