-
int and unsignd short
Hi,
I made a simple function that gets and prints tomorrow's date but it doesn't work.
It works only if I switch all "unsigned short" to regular "int".
I think there's a problem with getting variables from "scanf". (I tried to change %d to %lu in scanf sentence but it's not working either.)
Can anyone explain why its working only with int and how I can make it working with unsigned short?
Code:
#include <stdio.h>
void printTomorrow(unsigned short month, unsigned short day, unsigned short year);
bool isLeapYear(unsigned short year); //check if it's a leap year
void main(void)
{
unsigned short month, day, year;
printf("Input the date of which you want to know tomorrow\n");
printf(">> ");
scanf("%d %d %d", &month, &day, &year); //I inputed "7 31 2008"
printf("year: %d month: %d day; %d\n", year, month, day); //check if all variables are inputed correctly. it doesn't. only variable "year" has right one, rest of them has 0.
printTomorrow(month, day, year);
}
void printTomorrow(unsigned short month, unsigned short day, unsigned short year)
{
static unsigned short lastDay[13]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(isLeapYear(year)){ //if inputed year is leap
lastDay[2]=29; //change Febrary's last day
}
if(month<1 || month>12 || day<1 || day>lastDay[month]) //error check
fprintf(stderr, "printTomorrow:: Incorrect date!\n");
else{
day++;
if(lastDay[month]<day){ //in case that inputed day is the last day of the month.
day=1;
month++;
if(month == 13){ //in case that inputed date is the last day of the year.
month=1;
year++;
}
}
printf("Tomorrow:: %d-%d-%d\n",month, day, year);
}
}
bool isLeapYear(unsigned short year)
{
if(year%400 == 0)
return 1;
else if(year%4 ==0 && year%100!=0)
return 1;
else
return 0;
}
-
scanf() assumes that you are telling the truth: scanf("%d", &shortUnsignedVar) will overwrite some random data after shortUnsignedVar, if the variable is the type that the name implies, as a short (in most modern compilers) is only 2 bytes long, and and int which scanf() thinks you have passed the address of is 4 bytes. If you use "%hd", scanf will store only a short, rather than a full integer.
If you are using gcc, then you can enable full warnings with "-Wall" on the command line, and it will tell you when you "mess up" with the format and corresponding arguments for both scanf and printf type functions.
--
Mats
-
Thanks matsp,
Your answer is very clear and helpful to me:)