Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square of a number being defined using #define

Tags:

c

I was just going through certain code which are frequently asked in interviews. I came up with certain questions, if anyone can help me regarding this?

I am totally confused on this now,

#include <stdio.h>
#include <conio.h>

#define square(x) x*x

main()
{
      int i, j;
      i = 4/square(4);
      j = 64/square(4);
      printf("\n %d", i);
      printf("\n %d", j);
      printf("\n %d", square(4));
      getch();
}

The output is:

 4
 64
 16

I am wondering, why did square(4) return 1 when I divided it? I mean, how can I get the value 4 and 64 when I divide it, but when used directly I get 16!!?

like image 402
Nagaraj Tantri Avatar asked Sep 15 '10 15:09

Nagaraj Tantri


People also ask

What is the use of #define directive?

The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.

What is macro in C?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

How do you check if a number is a square number in C?

Store it's square root in a float variable fVar=4.000. Assign fVar into iVar (an integer variable) iVar=fVar, it means iVar will contain 4. Now compare iVar and fVar value will be equal. If number does not a perfect square, iVar and fVar will not same.


1 Answers

square is under-parenthesized: it expands textually, so

#define square(x) x*x
   ...
i=4/square(4);

means

i=4/4*4;

which groups as (4/4) * 4. To fix, add parentheses:

#define square(x) ((x)*(x))

Still a very iffy #define as it evaluates x twice, so square(somefun()) calls the function twice and does not therefore necessarily compute a square but rather the product of the two successive calls, of course;-).

like image 197
Alex Martelli Avatar answered Nov 10 '22 10:11

Alex Martelli