-2
#include<stdio.h>  
#define sqr(i) i*i

int main()
{ 
        printf("%d %d", sqr(3), sqr(3+1));  //output 9,7
        return 0;`
}

why the out put is 9,7? can anybody explain with steps how that 7 is getting evaluated

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Newbie
  • 204
  • 1
  • 3
  • 13
  • 1
    Which part of it is unclear? – Kerrek SB Jul 24 '16 at 14:22
  • If you get that comma separated output, then it is indeed a mystery. – Jongware Jul 24 '16 at 14:26
  • @RadLexus The OP probably doesn't know that the difference is important. – peterh Jul 24 '16 at 20:27
  • I would like to vote to reopen your question, because it is not a duplicate on my opinion. My problem is that you didn't even try to follow the [lowest spelling English standards](http://meta.stackoverflow.com/questions/291362/advice-for-non-native-english-speakers/291370#291370) and thus it would poll the site. So I need to vote for leave it closed. – peterh Jul 24 '16 at 20:28

2 Answers2

2

The macro sqr(i) i*i for sqr(3+1) will be evaluated to 3+1*3+1 which is ... 7. Put the arguments of the macro in parentheses:

#define sqr(i) (i) * (i)

if you really want to use a macro for this.

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
0

You are using the macro you define but the definition is a pitfall itself:

#define sqr(i) i*i

when you do this sqr(3) then this will be replaced and executed as 3*3 resulting 9

BUT HERE IS THE PROBLEM

sqr(3+1) will be replaced and executed as 3+1*3+1 resulting 3+3+1 =7

because the parameter will not be resolved before is passed to the macro...

instead it will just make a dumb-replace, changing every coincidence of i for the parameter 3+1

Ergo:

your macro behaves

input    output 

3          9 
3+1        7 
4          16
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97