Home > OS >  Inability to understand the output of a c program
Inability to understand the output of a c program

Time:02-28

I have come across a c program in a interview question .The program is as follow:

#include<stdio.h>
#define x 9 2/4*3-2*4 (5-4)*3
void main()
{

   int i,y,p;
   y=6 3*3/5;
   printf("%d",x);
   i=x*x y;
   printf("%d",i);

}

The output of this program is 30.But I can't understand how the program produce 30.Can anyone explain ?

CodePudding user response:

#define, in your specific case, does simple text replacement.

First expression (for x) is

9 2/4*3-2*4 (5-4)*3
9  0 *3-2*4   1  *3
9   0  - 8      3
  9    - 8      3
     1          3
          4      

Second expression (for i) is

9 2/4*3-2*4 (5-4)*3*9 2/4*3-2*4 (5-4)*3 y // y is 7
9 2/4*3-2*4 (5-4)*3*9 2/4*3-2*4 (5-4)*3 7 // doing parenthesis
9 2/4*3-2*4   1  *3*9 2/4*3-2*4   1  *3 7 // doing multiplications and divisions
9  0 *3- 8      3  *9  0 *3- 8      3   7 // doing multiplications and divisions again
9    0 - 8      27      0  - 8      3   7 // doing addition and subtraction left to right
   9   - 8      27      0  - 8      3   7
       1        27      0  - 8      3   7
            28          0  - 8      3   7
                28         - 8      3   7
                      20            3   7
                               23       7
                                   30

When writing #defines with operations always enclose the whole thing inside an extra set parenthesis:

#define x (9 2/4*3-2*4 (5-4)*3)

CodePudding user response:

Integer division is part of the answer, but the trickier part is the #define. Many people assume that a #define is evaluated when it is defined, but it is really just a simple text substitution. So when you are given x*x, you get

9 2/4*3-2*4 (5-4)*3*9 2/4*3-2*4 (5-4)*3

Note that is the middle of this you have 3*9, which you would not get if you assumed x was a simple numeric value. Heres the whole process:

  x * x
= 9 2/4*3-2*4 (5-4)*3*9 2/4*3-2*4 (5-4)
= 9    0 - 8      27      0  - 8    3
=        1        27   -     5
=              23

Then, since y=7, 23 7 = 30

Voila

  •  Tags:  
  • c
  • Related