Confused by squaring macro SQR in c [duplicate]

SQR(1+1) expands to 1+1*1+1 which is 3, not 4, correct?

A correct definition of the macro would be

#define SQR(x) ((x)*(x))

which expands to (1+1)*(1+1) and, more important, shows you one of the reasons you shouldn’t use macros where they aren’t needed. The following is better:

inline int SQR(int x)
{
    return x*x;
}

Furthermore: SQR(i++) would be undefined behavior if SQR is a macro, and completely correct if SQR is a function.

Leave a Comment