This code is interrupted randomly, correctly identifying some numerical palindromes and does not work 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 that "87678" is not a numeric palindrome.
Checking the return scanf() shows that it is succeeding, and printing the value of n correct for input 87678.
However, the code correctly says that "4554" is a palindrome.
However, adding:
n = reverse = temp = 0;
before the first printf() program runs correctly all the time. So what happens in the first version? Is this some kind of undefined behavior when variables are not initialized before use?
EDIT: will later provide an assembly of the compiled version that does not see what the compiler does.
source share