Explain what the following one-line function does and precisely how it does it.
void myStrcpy( char* a, char* b){ while (*a++ = *b++) ; }
In particular,
- What is the value of *b++?
- What is the boolean value of *a++ = *b++?
- What does the ++ operator increment?
- What is the body of the while loop?
- When and why does the loop terminate?
- What are its preconditions?
The function copies the data in C-string b into C-string a, as long
as the following preconditions are satisfied.
- The storage allocated for C-string a by the caller
is sufficient to hold all the data in C-string b.
- C-string b is null-terminated.
Suppose, for example, that b holds the string "Bananas",
and that a holds the address of some character array with at least
8 characters ( 8 chars = 7 data chars + 1 null char ).
Initially, b holds the address of the letter B,
the first char in its string. Recall that
- The value of b++ is the
same as the value of b before the pointer b
is incremented.
- The postfix increment operator (++)
has higher precedence than the deference operator (*).
Hence, the initial value of *b++ is just the character B,
in the above example. The function proceeds by copying this character
into the first slot in the array pointed at by a. After the copy,
both pointers are incremented, and at the next iteration, the second
character in b (the first letter 'a' in "Bananas")
will be copied. At each subsequent iteration of the loop,
the next character in b
is copied into the corresponding slot in a.
The value of an assignment statement x = y
is the boolean value of the value being copied. In the myStrcpy
function, the values being copied are characters. The only character
with boolean value false is the null character (ASCII value 0).
Immediately after the trailing null character is copied from b
to a, the loop condition evaluates to false, and the loop terminates.
Since all the work for the loop is done in its header,
there is no need for anything to be done in its body. However,
the C++ grammar still requires a body; hence, a semi-colon
or empty pair of brackets { } must appear after the while
header for correct compilation.
The precondition for the function is that the size of the array a[]
must be large enough to hold all the data being copied into it from
b[].
If a[] isn't large enough, disastrous consequences may result!