Reputation: 17
I have this code from the "Sams teach yourself C" book and it just doesnt work with the function definition outside the main function (after the function). I have got this program to run by putting the function definition in the main function in the beginning.
Why cant my CodeBlocks program use the function definition when its coded exactly as in the smart C book that I am learning from?
The code from the book:
#include <stdio.h>
#define TARGET_AGE 88
int year1, year2;
int calcYear(int year1);
int main( void )
{
// Ask the user for the birth year
printf( "What year was the subject born? ");
printf( "Enter as a 4-digit year (YYYY): ");
scanf( " %d", &year1);
// Calculate the future year and display it
year2 = calcYear(year1);
printf( "Someone born in %d will be %d in %d.",
year1, TARGET_AGE, year2);
return 0;
/* The function to get the future year */
int calcYear(int year1)
{
return(year1+TARGET_AGE);
}
}
Upvotes: 0
Views: 41
Reputation: 223872
While the declaration calcYear
is outside of main
, you're attempting to nest the definition of calcYear
function inside of the main
function. While some compilers accept this as an extension, many don't. Even on those that do, in my experience it's of limited usefulness.
Move the definition of calcYear
outside of main
.
#include <stdio.h>
#define TARGET_AGE 88
int year1, year2;
int calcYear(int year1);
int main( void )
{
// Ask the user for the birth year
printf( "What year was the subject born? ");
printf( "Enter as a 4-digit year (YYYY): ");
scanf( " %d", &year1);
// Calculate the future year and display it
year2 = calcYear(year1);
printf( "Someone born in %d will be %d in %d.",
year1, TARGET_AGE, year2);
return 0;
}
/* The function to get the future year */
int calcYear(int year1)
{
return(year1+TARGET_AGE);
}
Upvotes: 1