This code fails randomly by correctly identifying some numeric palindromes and failing on others.
#include <stdio.h>
int main(int argc, char *argv[])
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
For example, the above code incorrectly says "87678" isn't a numeric palindrome.
Checking the return of scanf()
shows it's succeeding and printing the value of n
is correct for input of 87678.
However the code correctly says "4554" is a palindrome.
However, by adding:
n = reverse = temp = 0;
before the first printf()
the program appears to work correctly all the time. So what is happening in the first version? Is this some sort of undefined behavior when the variables aren't initialized before use?
EDIT: Will later provide the assembly of the compiled version that is failing to see what the compiler is doing.