0

So, I'm confused why the output of i would be 27 and not 343

 #include <stdio.h>
#define x 5+2
void main() {
int i;
i=x*x*x;
printf("%d",i); }
  • 4
    It expands to `5+2*5+2*5+2`. – kaylum Feb 21 '20 at 09:06
  • 1
    Does this answer your question? [The need for parentheses in macros in C](https://stackoverflow.com/questions/10820340/the-need-for-parentheses-in-macros-in-c) – phuclv Feb 21 '20 at 09:21
  • 1
    there are a lot of duplicates: [Confused by squaring macro SQR in c](https://stackoverflow.com/q/17071504/995714), [Incorrect answer from #define SQR(x) (x*x)](https://stackoverflow.com/q/25822341/995714). And this should be explained in every book. [The Definitive C Book Guide and List](https://stackoverflow.com/q/562303/995714) – phuclv Feb 21 '20 at 09:22
  • OT: regarding the statement: `void main() {` 1) in C, there are only two valid signatures for `main()` They are: `int main( void )` and `int main( int argc, char *argv[] )` Note: they both have a return type of `int`, not `void`. This statement will cause a compiler to output a warning message. – user3629249 Feb 22 '20 at 22:42

1 Answers1

13

Let's expand what you did, preprocessor is a dummy thing that just replaces the token with text

i = 5+2*5+2*5+2; // <- 27

if you modify define to be #define x (5+2) all should work as expected.

Tarek Dakhran
  • 2,021
  • 11
  • 21