user2923535
user2923535

Reputation: 594

Using #define in c for equations

Can someone explain to me why the value of y here is 13?

#include <stdio.h>
#define avg_sum(n) n * (n-1)/2
int main(){
    int y;
    int z = 9;
    y = avg_sum(z+1);
    printf("y=%i\n",y);
}

Upvotes: 3

Views: 6808

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124790

The best way to answer these sorts of questions is to simply expand the macro in question:

y = avg_sum(z+1);

y = z + 1 * (z + 1 - 1) / 2

y = 9 + 1 * (9 + 1 - 1) / 2

y == 13

This is why you add parentheses around your macro arguments.

#define avg_sum(n) ((n) * ((n)-1)/2)

Upvotes: 5

Glenn Teitelbaum
Glenn Teitelbaum

Reputation: 10343

avg_sum(9+1) 9+1 * (9+1-1)/2 = 9 + 9/2 = 9+ 4 = 13

macros expand each time so 9+1 is not the same as 10, it might be better with safeguarding parenthesis as follows:

#define avg_sum(n) ((n) * ((n)-1)/2)

but an equivelant function will do you much better and be more intuitive and will evaluate arguments only once

avg_sum(a++) will be ((a++) * ((a++)-1)/2) and will increment a twice whereas a function will not have these issues since all arguments are evaulated before the function is called

Upvotes: 9

Deck
Deck

Reputation: 1979

y = avg_sum(z+1);

expands to z + 1 * (z+1-1)/2 but it's wrong. Change your macro to

#define avg_sum(n) ((n) * ((n)-1)/2)

And always parenthesize as well arguments of functional macros as the macro itself . It's an important rule.

Upvotes: 2

Related Questions