Sams Teach Yourself C++ in 21 Days

(singke) #1

Q&A ....................................................................................................................


Q Why not make all variables global?
A At one time, this was exactly how programming was done. As programs became
more complex, however, it became very difficult to find bugs in programs because
data could be corrupted by any of the functions—global data can be changed any-
where in the program. Years of experience have convinced programmers that data
should be kept as local as possible, and access to changing that data should be nar-
rowly defined.
Q When should the keyword inlinebe used in a function prototype?
A If the function is very small, no more than a line or two, and won’t be called from
many places in your program, it is a candidate for inlining.
Q Why aren’t changes to the value of function arguments reflected in the calling
function?
A Arguments passed to a function are passed by value. That means that the argument
in the function is actually a copy of the original value. This concept is explained in
depth in the section “How Functions Work—A Peek Under the Hood.”
Q If arguments are passed by value, what do I do if I need to reflect the changes
back in the calling function?
A On Day 8, pointers will be discussed and on Day 9, you’ll learn about references.
Use of pointers or references will solve this problem, as well as provide a way
around the limitation of returning only a single value from a function.
Q What happens if I have the following two functions?
int Area (int width, int length = 1); int Area (int size);
Will these overload? A different number of parameters exist, but the first one
has a default value.
A The declarations will compile, but if you invoke Areawith one parameter, you will
receive an error: ambiguity between Area(int, int)and Area(int).

Workshop ............................................................................................................


The Workshop provides quiz questions to help you solidify your understanding of the
material covered and exercises to provide you with experience in using what you’ve
learned. Try to answer the quiz and exercise questions before checking the answers in
Appendix D, and be certain that you understand the answers before continuing to tomor-
row’s lesson.

134 Day 5

Free download pdf