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!!?
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.
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.
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.
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;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With