The posted code uses the following algorithm:
- Line 7: set the pointer
t
to the last character in the string (note: it will be a newline character if the user entered a string fewer than 99 characters). The -1
is to move one character back from the terminating nil-char
- Lines 8-10: This is the core of the reversal reporting loop. The pointer
t
is repeatedly tested against the address at the beginning of the string. The condition clause checks to see if the t
value (an address) is greater-or-equal to the beginning address of the string. So long as it is, the loop-body is entered and the character currently residing at the address held in t
is sent to stdout via printf()
. The address in t
is then decremented by one type-width (one-byte on most-all systems with a single-byte char
) and the loop repeats. Only when t
contains an address before s
does the loop break (and note: this is not within the standard; see below for why).
Something you should know about this loop (and should point out to the author if it isn't you). The final pointer comparison is not standard-compliant. The standard specifies comparison between non-null, like-type, pointers is valid from the base address of a valid sequence (charinput
in this code, the address parameterized through s
) up to and including one type-element past the allocated region of memory. This code compares t
against s
, breaking the loop only when t
is "less". But as soon as t
is less-than-s its value is no longer legally range-comparable against s
. In accordance with the standard, this is so because t
no longer contains a valid address that falls in the range from charinput
through 1-past the size of the charinput
memory block.
One way to do this correctly is the following:
t = s + len;
while (t-- > s)
printf("%c", *t);
Edit: after a journey into the standard after prodding from Paul Hankin the prior code has been rewritten to account for an unnoticed UB condition. The updated code is documented below:
t = s + len;
while (t != s)
printf("%c", *--t);
This will also work for zero-length strings. How it works is as follows:
t
is set to the address of the terminating nulchar of the string.
- Enter the loop, the condition being continue so long as the address in
t
is not equivalent to the base address of s
.
- Decrement
t
, then dereference the resulting address to obtain the current character, sending the result to printf
.
- Loop around for next iteration.