Plochie
Plochie

Reputation: 4117

C macro with expression unwanted result

I am running the following program and getting a result as 9 7, I understood why 9 is the output but I can't figure out why I'm getting 7 as output.

#include<stdio.h>
#define sqr(i) (i*i)

int main()
{
    printf("%d %d", sqr(3), sqr(3+1));
    return 0;
}

For the second function that is sqrt(3+1) how the micro is getting expanded and how Im getting 7 output?

Upvotes: 1

Views: 62

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90681

You can have the compiler or IDE preprocess the file and show you how the macro expanded.

In your case sqr(3+1) expands to (3+1*3+1). Now the precedence of C operators means that the multiplication is done before the addition. So (3+1*3+1) -> (3+3+1) -> (7).

You can fix this by defining your macro this way, with parentheses around the argument:

#define sqr(i) ((i)*(i))

Upvotes: 4

Related Questions