'Strange value when printing out integer [closed]

#include <stdio.h>

int leapyear(int year)
{
    if((year % 4 != 0) && (year % 400 != 0) || (year % 100 == 0))
    {
        printf("Year %d is not leap year.\n", year);
        return 0;
    }
    else
    {
        printf("Year %d is leap year.\n", year);
        return 1;
    }
}

int addDate(int month, int date)
{
     int i, febDate = 0, sum = 0, year;
     if(leapyear(year) == 1)
     {
        febDate += 29;
     }
     else
     {
        febDate += 28;
     }
     for(i = 1; i < month; i++)
     {
         if((i <= 7) && (i != 2) && (i % 2 == 0)) 
         {
             sum += 30;
         }
         else if(i == 2)  
         {
             sum += febDate;
         }
         else if((i >= 8) && (i % 2 != 0)) 
         {
             sum += 30;
         }
         else 
         {
             sum += 31;
         }
      }
    return sum + date;
}

int main(void)
{
    int month, date, year;
    printf("Enter Month: ");
    scanf("%d", &month);
    printf("Enter Date: ");
    scanf("%d", &date);
    printf("Enter Year: ");
    scanf("%d", &year);
    leapyear(year);
    printf("%d days from Jan 1st to %d %d.\n", addDate(month, date), month, date);
    return 0;
}

When I put in 8 22, 2016, I get the following:

Enter Month: 8
Enter Date: 22
Enter Year: 2016
Year 2016 is leap year.
Year -1249813628 is leap year.
235 days from Jan 1st to 8 22.

Everything looks okay except for that "Year -1249813628 is leap year." part.

What could be causing this? I tried having the main function at the very top but didn't fix the problem.



Solution 1:[1]

In the addDate function you call leapyear again, but now with the uninitialized local variable year.

Uninitialized local variables will have an indeterminate value (think of it as garbage). In C++ using indeterminate values will lead to undefined behavior.

You should pass year as an argument to the function instead.

int addDate(int year, int month, int date)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some programmer dude