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:
#define AGE 15;
float myAge = AGE + 1;
printf("My name is Raz and I am %d years old!\n", myAge);
#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
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 AGE 15
Better yet, avoid using the preprocessor for simple numerical constants - consider using a
const int instead:
const int age = 15;