Reputation: 91
#include <stdio.h>
int main()
{
int var;
printf("write the value of var:\n");
scanf("%d", &var);
#define NUM var
printf("The value of S is %d\n", NUM);
var = var + 1; //changing the value of variable 'var'
printf("New value of S is %d", NUM);
return 0;
}
Following is the result...
write the value of var:
10
The value of S is 10
New value of S is 11
[Program finished]
In this program, I want to make constant the value of variable 'var' once it's entered by user. so, I have defined a macro with macro templet 'NUM' and macro expansion 'var'. But when I change the value of 'var' on execution time then the value of 'NUM' also get changed. Don't know how? Actually I don't know that can we use any variable in macro expansion ?
Upvotes: 0
Views: 275
Reputation: 67741
Preprocessing is done before the actual C code compilation. It simply textually replaces the token NUM
with token var
.
So after the preprocessing your function is:
int main()
{
int var;
printf("write the value of var:\n");
scanf("%d", &var);
printf("The value of S is %d\n", var);
var = var + 1; //changing the value of variable 'var'
printf("New value of S is %d", var);
return 0;
}
This main
function is being compiled. As you see the NUM
has been replaced with var
and the result is obvious.
Upvotes: 2