20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Functions and Structures<br />

173<br />

Program 9.3<br />

Cont<strong>in</strong>ued<br />

// Function to determ<strong>in</strong>e if it's a leap year<br />

bool isLeapYear (struct date d)<br />

{<br />

bool leapYearFlag;<br />

if ( (d.year % 4 == 0 && d.year % 100 != 0) ||<br />

d.year % 400 == 0 )<br />

leapYearFlag = true; // It's a leap year<br />

else<br />

leapYearFlag = false; // Not a leap year<br />

}<br />

return leapYearFlag;<br />

Program 9.3 Output<br />

Enter today's date (mm dd yyyy): 2 28 2004<br />

Tomorrow's date is 2/29/04.<br />

Program 9.3 Output (Rerun)<br />

Enter today's date (mm dd yyyy): 2 28 2005<br />

Tomorrow's date is 3/1/05.<br />

The first th<strong>in</strong>g that catches your eye <strong>in</strong> the preced<strong>in</strong>g program is the fact that the def<strong>in</strong>ition<br />

of the date structure appears first and outside of any function.This makes the<br />

def<strong>in</strong>ition known throughout the file. Structure def<strong>in</strong>itions behave very much like<br />

variables—if a structure is def<strong>in</strong>ed with<strong>in</strong> a particular function, only that function knows<br />

of its existence.This is a local structure def<strong>in</strong>ition. If you def<strong>in</strong>e the structure outside of<br />

any function, that def<strong>in</strong>ition is global.A global structure def<strong>in</strong>ition allows any variables<br />

that are subsequently def<strong>in</strong>ed <strong>in</strong> the program (either <strong>in</strong>side or outside of a function) to<br />

be declared to be of that structure type.<br />

Inside the ma<strong>in</strong> rout<strong>in</strong>e, the prototype declaration<br />

<strong>in</strong>t numberOfDays (struct date d);<br />

<strong>in</strong>forms the C compiler that the numberOfDays function returns an <strong>in</strong>teger value and<br />

takes a s<strong>in</strong>gle argument of type struct date.<br />

Instead of compar<strong>in</strong>g the value of today.day aga<strong>in</strong>st the value<br />

daysPerMonth[today.month - 1], as was done <strong>in</strong> the preced<strong>in</strong>g example, the statement<br />

if ( today.day != numberOfDays (today) )

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!