Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am unable to understand the execution of following c code [duplicate]

Tags:

c

#include <stdio.h>

#define sqr(a) a*a

int main()
{
    int i;

    printf("%d",64/sqr(4));

    return 0;
}

Why am I getting the output as 64 .

Normally what should happen is it first checks the value for sqr(4) and then divide . In case of any other operator it works fine .

Please Explain .

like image 934
Bharat Jain Avatar asked Aug 09 '15 17:08

Bharat Jain


1 Answers

After preprocessing the printf line will be:

printf("%d",64/4*4);

which should explain why it prints 64.

Always use parenthesis in macros definitions when they contain expressions:

#define sqr(a) ((a)*(a))

Even this is not safe against macro invocations like: sqr(x++). So don't use marcos unless you have to :)

like image 178
P.P Avatar answered Sep 28 '22 14:09

P.P