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);
}
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
static inline int avg_sum(int n) { return (n * (n-1)) / 2; } works nicely, unless you're stuck with an archaic C90 compiler (eg the default on Windows, MSVC).(n-1)/2 is evaluated before it is multiplied by n: suppose n == 4. Then (n-1)/2 is 1 and n*1 is 4; OTOH, (4 * 3)/2 is 6. I think the parentheses do matter, if the compiler is allowed to reorder operations, and I think it is.5 | * / % | Multiplication, division, and remainder | left to right No reordering allowed - no parens needed
934 / avg_sum(12)gives you the expected answer too.