c - Why the analyzation of code isn't right? -


why output "0 -6" , not "4 60"? isn't k=8, l=2?

#define mac(a,b) (a<b ? a*b:a-b) void main (void) {    int i=2;    int j=4;    int k=mac(i,j);    int l=mac(j,i);    i=mac(k+l,k-l);    j=mac(k-l,k+l);    printf("%d %d\n", i,j); } 

one immediate problem. expression

mac(k+l,k-l) 

becomes

(k+l<k-l ? k+l*k-l:k+l-k-l)            ^^^^^^^ 

and, can see underlined bit, expression not think due precedence rules (multiplication done before addition).

this can fixed ensuring each argument in macro parenthesised:

#define mac(a,b) ((a)<(b) ? (a)*(b):(a)-(b)) 

but still won't if pass in n++ incremented multiple times.

macros simple text substitutions , known cause problems such you're seeing. advice turn mac proper function avoid problem completely, like:

int mac (int a, int b) {     if (a < b)         return * b;     return - b; } 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -