Raz Omry Raz Omry - 19 days ago 6
C Question

strange behavior of #define command

I've tried to figure out this behavior of the define command in C (I'm new with that). I've got this code and I don't know why I see in the output that myAge=15 and not 16 (I know it's 15, but I don't know why). Anybody can help me to find out why does it happen?

this is the code:

#include <stdio.h>
#include <stdlib.h>
#define AGE 15;

int main(void)
{
float myAge = AGE + 1;
printf("Hello!\n");
printf("My name is Raz and I am %d years old!\n", myAge);

system("PAUSE");

return 0;
}


Thanks for helping :)

Answer

#define is a textual replacement performed by the preprocessor prior to the compilation step. In this case, you're asking the preprocessor to expand the token AGE to 15;. The semicolon is part of the expansion, so this is the code you would get after the preprocessing step:

float myAge = 15; + 1;

As you can see, it does not expand to what you expect.

You can fix this issue by removing the semicolon from the #define:

#define AGE 15

Better yet, avoid using the preprocessor for simple numerical constants - consider using a const int instead:

const int age = 15;