I have written the following C program. The output is 32. Why is this?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define max 10+2
int main(){
int i;
i = max * max;
printf("\n%d\n",i);
return 0;
}
(I am learning C and am relatively new to it.)
This is the preprocessor. it is not smart.
it is stupid.
it just replaces text.
will resolve to
which is
because of operator precedence, which is
i.e.
32Furthermore, you should avoid preprocessor macros whenever you can and use. You may or may not want to also consider using astatic constinsteadconstvariable or anenuminstead of a#define; each have their tradeoffs, refer to the similar question: "static const" vs "#define" vs "enum".If you want to stick to preprocessor, then you could just use:
Since parenthesised code will take operator precendence.