I recently had a test in my class. One of the problems was the following:
Given a number n, write a function in C/C++ that returns the su
Summarizing a discussion that's been percolating in the comments:
n == 0
. The while(n)
test will handle that case perfectly.%
with negative operands was differently defined. On some old systems (including, notably, early Unix on a PDP-11, where Dennis Ritchie originally developed C), the result of a % b
was always in the range [0 .. b-1]
, meaning that -123 % 10 was 7. On such a system, the test in advance for n < 0
would be necessary.But the second bullet applies only to earlier times. In the current versions of both the C and C++ standards, integer division is defined to truncate towards 0, so it turns out that n % 10
is guaranteed to give you the (possibly negative) last digit of n
even when n
is negative.
So the answer to the question "What is the meaning of while(n)
?" is "Exactly the same as while(n != 0)
", and the answer to "Will this code work properly for negative as well as positive n
?" is "Yes, under any modern, Standards-conforming compiler." The answer to the question "Then why did the instructor mark it down?" is probably that they're not aware of a significant language redefinition that happened to C in 1999 and to C++ in 2010 or so.