0

int in function vs int before function

Need some help knowing what I'm doing wrong. I was doing the palindrome question on C++ and here is the code i was using that always output that it was not a palindrome: #include <iostream> using namespace std; bool isPalindrome(int x) { //complete the function int newx, reversex, remainder; newx = x; while (newx!=0) { remainder = newx%10; reversex = reversex*10 + remainder; newx /= 10; } if (x==reversex) { return true; } else return false; } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; } All i had to do in order to make the code work correctly was declare int reversex before the bool function, like this: #include <iostream> using namespace std; int reversex; bool isPalindrome(int x) { //complete the function int newx, remainder; newx = x; while (newx!=0) { remainder = newx%10; reversex = reversex*10 + remainder; newx /= 10; } if (x==reversex) { return true; } else return false; } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; } Can anyone tell me why this is?? Thanks in advance.

3rd Jan 2022, 3:52 PM
Christopher Blankenship
Christopher Blankenship - avatar
2 Réponses
+ 2
Christopher Blankenship In your first code , reversex is containing garbage value by default. Initialize it to 0 first then code will work fine. In your second code, reversex is a global variable. By default Global variables are automatically initialized to 0 at the time of declaration. That is why it is already working fine. reference: https://www.tutorialspoint.com/why-are-global-and-static-variables-initialized-to-their-default-values-in-c-cplusplus
3rd Jan 2022, 4:06 PM
saurabh
saurabh - avatar
+ 1
Christopher Blankenship You are using temporary variable newx in while loop, instead you should use x like while (x != 0) { reminder = x % 10; reversex = reversex * 10 + reminder; x /= 10; } Now compare temporary variable newx with reversex if (newx == reversex) return true; else return false; or you can directly return like this: return (newx == reversex); ------------xxxx------- bool isPalindrome(int x) { //complete the function int newx, reversex; newx = x; while (x != 0) { reversex = reversex * 10 + x % 10; x /= 10; } return (newx == reversex); }
3rd Jan 2022, 4:09 PM
A͢J
A͢J - avatar