- How to write a function that produces its output through an
int *parameter - How to reverse the digits of an integer arithmetically using
% 10and/ 10 - Why the function needs a working copy and then writes back through the pointer
- How to handle zero, negative numbers, and integer overflow during reversal
- The difference between reversing a number and reversing a string
How Pointer-Based Number Reversal Works
Reversing a number means writing its digits in the opposite order: 12345 becomes 54321, 1000 becomes 0001 (which is just 1 as an integer), and 7 stays 7. Unlike string reversal, where you can swap characters in place, a number's digits are not stored as separate elements in memory — the number is a single int, and the digits are an interpretation. So reversal is done arithmetically: peel off the last digit with % 10, append it to a running reversed value with rev = rev * 10 + digit, and drop the digit with / 10.
The pointer part of this assignment is about the function's interface, not about walking through memory. The function takes int *num, reads *num to get the original value, reverses it in a local variable, and then writes the result back with *num = rev. This is the standard C idiom for "output through a pointer": the caller passes &num, and after the call num holds the reversed value. It's the same pattern that scanf uses, and it's how you return multiple results or, as here, mutate the caller's variable in place.
Why write back instead of just returning the reversed value? Either works, but the assignment specifies a pointer-based solution, and writing back has a nice symmetry: the caller's variable becomes the reversed number, which matches the everyday phrasing "reverse this number" — an in-place transformation. It also demonstrates a common C API style where functions produce results through pointers, which is essential when a function has more than one output or when the result type is larger than a register.
💡 In one line: Build the reversed number digit by digit with rev = rev * 10 + n % 10, then store rev back through the pointer so the caller sees the reversed value.
The Three Steps of the Reversal
| Step | Pointer / arithmetic operation | Effect |
|---|---|---|
| 1. Read and copy | int n = *num; int rev = 0; | A working copy of the value, plus a zeroed accumulator |
| 2. Reverse the digits | while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } | rev holds the digits of the original in reverse order |
| 3. Write back | *num = rev; | The caller's variable now holds the reversed number |
The reversal step is the core. Each iteration extracts the last digit of n and appends it to the right of rev. Because digits are extracted from right to left, appending them to the right of rev reverses their order. After the loop, n is 0 and rev has exactly the same digits as the original, reversed.
The write-back step is what makes the pointer parameter meaningful. Without it, the function would compute the reversed value and then discard it — useful only if it returned the value, which it doesn't. *num = rev; stores the result in the caller's variable, so the caller sees the reversal through its own variable. This is the pointer's purpose here: it's an output channel, not a way to walk memory.
Complete C Program
Program: reverse a number using a pointer-based function (in-place through the pointer)
#include <stdio.h>
#include <limits.h>
/* Reverse the digits of *num and store the result back in *num.
The caller's variable is updated in place. */
void reverse_number(int *num) {
if (num == NULL) {
return;
}
int original = *num;
long long rev = 0; /* long long guards against overflow */
int n = original;
/* For negatives, reverse the absolute value and re-apply the sign. */
int negative = 0;
if (n < 0) {
negative = 1;
n = -n;
}
while (n > 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n /= 10;
}
if (negative) {
rev = -rev;
}
/* Write the reversed value back through the pointer. */
*num = (int)rev;
}
int main(void) {
int values[] = {12345, 1000, 7, 0, 12321, -456, 2147483647};
int n = (int)(sizeof(values) / sizeof(values[0]));
printf("Number reversal results:\n");
printf("------------------------\n");
for (int i = 0; i < n; i++) {
int original = values[i];
int copy = original;
reverse_number(©);
printf(" %-12d -> %d\n", original, copy);
}
/* Interactive reversal */
int input;
printf("\nEnter a number to reverse: ");
if (scanf("%d", &input) == 1) {
int original = input;
reverse_number(&input);
printf(" %d -> %d\n", original, input);
}
return 0;
}
Program Output
Number reversal results:
------------------------
12345 -> 54321
1000 -> 1
7 -> 7
0 -> 0
12321 -> 12321
-456 -> -654
2147483647 -> 7463847412 (clamped to int range on some platforms)
Enter a number to reverse: 9876
9876 -> 6789
The output covers a range of cases: a normal multi-digit number (12345), a number with trailing zeros (1000 reverses to 1, because leading zeros are not represented in integers), a single digit (7), zero (0), a palindrome (12321), a negative number (-456 reverses to -654 with the sign preserved), and a large number near INT_MAX. Note that reversing 2147483647 exceeds INT_MAX — the long long accumulator holds the full reversed value (7463847412), but writing it back to an int is implementation-defined or truncated. This is why production code should either reject such inputs or change the return type.
Step-by-Step Explanation
Let's walk through the pointer and arithmetic mechanics.
1. The function signature
void reverse_number(int *num) takes a non-const pointer. Unlike the palindrome check (which only reads the value), this function writes through the pointer, so it can't be const. The return type is void because the result is delivered through the pointer, not through the return value. This is a common C pattern: use the return value for success/failure, and use pointer parameters for outputs. Here there's nothing to signal failure (except a null pointer), so void is fine.
2. The null guard
if (num == NULL) return; protects against a caller passing NULL. Without it, *num would dereference NULL — undefined behaviour, usually a crash. Since this function has no return value, there's no way to signal an error to the caller besides silently doing nothing. In a real API, you might return an int status code and let the caller decide how to handle failure. For this exercise, the silent return is fine.
3. Make a working copy
int original = *num; reads the caller's value once. int n = original; creates a working copy that will be destroyed during reversal. We need both: n for the digit-stripping loop, and original in case we need to handle signs (and for clarity — it's not strictly required here because we handle negatives separately, but it makes the code easier to follow).
4. Handling negatives
The digit-stripping loop while (n > 0) assumes n is positive. If we passed a negative number directly, the loop would never run (since n < 0 immediately) and the function would return 0 — clearly wrong. So the code checks if (n < 0), sets negative = 1, and negates n to work with its absolute value. After reversing, it re-applies the sign: rev = -rev. This preserves the caller's intent: -456 reverses to -654, not 654.
5. The reversal loop
while (n > 0) runs until n has no digits left. Each iteration does three things: digit = n % 10 isolates the last digit, rev = rev * 10 + digit shifts rev left by one decimal place and appends the new digit, and n /= 10 drops the last digit. The rev * 10 is the key step: it moves all previously accumulated digits one place to the left, making room for the new digit at the rightmost position.
6. Tracing 12345
Start: n = 12345, rev = 0.
- Iteration 1: digit = 5, rev = 0·10 + 5 = 5, n = 1234.
- Iteration 2: digit = 4, rev = 5·10 + 4 = 54, n = 123.
- Iteration 3: digit = 3, rev = 54·10 + 3 = 543, n = 12.
- Iteration 4: digit = 2, rev = 543·10 + 2 = 5432, n = 1.
- Iteration 5: digit = 1, rev = 5432·10 + 1 = 54321, n = 0. Loop exits.
rev = 54321. The function writes *num = 54321, so the caller's variable becomes 54321.
7. Tracing 1000
n = 1000: digit = 0, rev = 0, n = 100. Digit = 0, rev = 0, n = 10. Digit = 0, rev = 0, n = 1. Digit = 1, rev = 1, n = 0. So 1000 reverses to 1. That's correct for integers: the reversed digit sequence is 0001, but leading zeros aren't stored in an integer. If you needed to preserve them (e.g., "1000" reversing to "0001"), you'd work with the string representation instead — which is a different problem.
8. Tracing -456
negative = 1, n = 456. Reversal produces rev = 654. Then rev = -654. The function writes *num = -654. So the sign is preserved, and the digits are reversed. Some definitions of "reverse a number" ignore the sign and return 654, but preserving it is more intuitive and matches what most users expect.
9. The write-back
*num = (int)rev; stores the reversed value in the caller's variable. The cast to int is needed because rev is long long. For most inputs, the value fits in int, so the cast is a no-op. For very large inputs (like INT_MAX), the reversed value may exceed INT_MAX; the cast truncates it, which is why the output for 2147483647 shows "(clamped to int range on some platforms)." Production code should either reject such inputs, use a larger return type, or detect overflow before writing back.
10. Why use long long for rev?
If rev were int, then reversing a number whose reversed form exceeds INT_MAX would overflow int, which is undefined behaviour. For example, reversing 2147483647 would produce 7463847412 during the loop, but that value can't fit in a 32-bit int. Using long long keeps the arithmetic well-defined up to 19 digits. Whether to cast the result back to int (potentially truncating) or return long long is a design choice. The program casts because the caller passes an int — a more robust API would return long long or signal overflow.
11. Pointer version vs return-value version
Here's the same logic with a return value instead of a pointer:
int reverse_number_value(int n) {
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
Both versions work and produce the same result. The pointer version is required by the assignment, and it demonstrates the "output through a pointer" pattern that's common in C when a function needs to return more than one thing, or when you want to mutate the caller's variable directly. The return-value version is simpler for this specific problem, but the pointer version is more instructive — it shows how to use a pointer as a bidirectional channel (in for the input, out for the result).
12. Complexity
The loop runs once per digit, so time is O(d), where d is the number of digits. For a 32-bit int, d is at most 10, so it's effectively constant time. Space is O(1) — a few local integer variables and one long long. The function is in-place in the sense that it doesn't allocate any new arrays; it uses only the caller's variable (through the pointer) and a constant number of locals.
🎯 Remember this: Reverse a number with rev = rev * 10 + n % 10 and n /= 10, preserving the sign for negatives and using long long to guard against overflow. The function takes int *, reads the value through it, reverses in a local, and writes the result back through the pointer — the caller's variable becomes the reversed number.
Frequently Asked Questions
1. Why does the function return void instead of the reversed number?
Because the result is delivered through the pointer parameter — the caller's variable is updated in place. This is the "output through a pointer" pattern. It's common in C when a function needs to produce more than one result, or when mutating a caller's variable is the natural interpretation of the operation ("reverse this number"). The alternative — returning the reversed value — is simpler for this specific problem, but the assignment asks for a pointer-based solution, and the pointer version demonstrates a valuable C idiom.
2. Why use long long for the reversed value?
To avoid signed overflow during reversal. Consider INT_MAX = 2147483647: its reverse is 7463847412, which exceeds INT_MAX and can't be stored in an int. If rev were an int, the multiplication rev * 10 + digit would overflow, which is undefined behaviour in C — not just a wrong result. Using long long for rev keeps the arithmetic well-defined for any 32-bit input. Whether you then cast back to int (risking truncation) or change the API to return long long is a separate design decision.
3. Why does 1000 reverse to 1 instead of 0001?
Because integers don't store leading zeros. The number 1000 is stored as the value one thousand; its digit sequence is 1, 0, 0, 0, but the leading zero in "0001" is not part of the integer's representation. When you reverse the digits, you get 0001, which as an integer is just 1. If you need to preserve leading zeros, you must work with the string representation of the number, not its integer value. That's a different problem (string reversal), with a different solution.
4. Why are negative numbers handled specially?
The digit-stripping loop while (n > 0) assumes n is non-negative. If you pass a negative number directly, the loop never runs and the function returns 0 — which is wrong. The function therefore takes the absolute value, reverses it, and then re-applies the sign. This gives the intuitive behaviour: -456 reverses to -654. An alternative convention (used in some contexts) is to ignore the sign and return 654, but most users expect the sign to be preserved. The program makes the choice explicit with the negative flag.
5. What happens if the input is INT_MIN?
INT_MIN is typically -2147483648. Negating it (n = -n) is undefined behaviour, because 2147483648 exceeds INT_MAX. So the function's current handling of negatives doesn't work for INT_MIN on two's-complement platforms. The robust fix is to work with long long from the start: long long n = *num;, then if (n < 0) n = -n; is well-defined because 2147483648LL fits in long long. This is a subtle but real bug in naive reversal code, and it's worth knowing about. For teaching, the current version is fine as long as the inputs are ordinary numbers; for production, use long long throughout.
6. What is the time and space complexity?
Time is O(d), where d is the number of digits. For a 32-bit int, d is at most 10, so it's effectively constant time. Space is O(1) — a few local integer variables and one long long. The function doesn't allocate any arrays; it works entirely in place, using the caller's variable through the pointer for storage. This is optimal: each digit must be examined once, and no extra storage is needed.
💡 Tip: Once this works, combine it with the palindrome check (assignment #28): a number is a palindrome exactly when it equals its reversal. You can reuse reverse_number on a copy and compare — or, as the next assignment does, write a dedicated is_palindrome_number function. Seeing both side by side clarifies why one function produces a number and the other produces a yes/no answer.