0

I wrote a simple code that checks if a number is 10 . If it is, the function returns 10.

int foo()
{
   if (n==10)
      return n;
}

I wrote another function to check if a number is a palindrome

int checkpalin(int n)
{
       int temp=n;
       double rev=0;
       while (temp)
       {
           int d=temp%10;
           rev=rev*10+d;
           temp/=10;
       }
       if (rev==n)
          return n;
}

I call and display the function like so:

cout<<foo(11)<<endl<<checkpalin(25)<<endl;  

When I pass any number other than ten and any non palindromic number to foo and checkpalin respectively I always get the following output:

1

16640

Any ideas why this happens?

Community
  • 1
  • 1
m0bi5
  • 8,900
  • 7
  • 33
  • 44

1 Answers1

2

Your function definitions don't specify what to return if the condition is not true. A function must always return something, so it just returns junk (although it may well be predictable junk, the value is undefined).

You should rewrite your functions like this:

int foo()
{
   if (n==10)
      return n;
   else
      return 0;
}
ams
  • 24,923
  • 4
  • 54
  • 75