Trung Đặng - 3 months ago 25

C Question

I'm quite confusing about this:

`#define prod(x,y) x*y`

The following function call prints

`11`

`printf("%d",prod(1+2,3+4));`

But when I use

`prod(x,y)`

`x*y`

Why the results are different? I thought

`#define`

`prod(x,y) = x*y`

Answer

Operator precedence is biting you.

With

```
#define prod(x,y) x*y
```

the line

```
printf("%d",prod(1+2,3+4));
```

gets expanded to

```
printf("%d",1+2*3+4);
```

Note that `*`

has higher precedence than `+`

, so this is evaluated as `1 + (2 * 3) + 4`

or `11`

.

**Solution:**

Surrround the parameters with parenthesis in your `#define`

:

```
#define prod(x,y) ((x)*(y))
```

The line will now be expanded to:

```
printf("%d",((1+2)*(3+4)));
```

The purpose of the extra set of parenthesis around the entire expression is to make the expression work as you want when used in conjunction with an operator where evaluation order matters.

`prod(4,3)/prod(1,2))`

gets expanded to `((4)*(3))/((1)*(2))`

or `6`

. Without the outer parenthesis the expansion would be `(4)*(3)/(1)*(2)`

or `24`

.