Raz Omry Raz Omry - 4 months ago 20
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("My name is Raz and I am %d years old!\n", myAge);


return 0;

Thanks for helping :)


#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;