-2

I just found that if i assign value of x as 5 inside the file and run it as in the following code i get output as 392

#include<stdio.h>
#define CUBE(r) ((r)*(r)*(r))
int main()
{
    int x;
    x=5;
    printf("%d\n", CUBE(++x));
    return 1;
}

But when i use "scanf()" to get the value of x and give input as 5 for the following code i get the output as 336

#include<stdio.h>
#define CUBE(r) ((r)*(r)*(r))
int main()
{
    int x;
    scanf(" %d",&x);
    printf("y is %d\n", CUBE(++x));
    return 1;
}

why i am get this kind of output

siva
  • 163
  • 4

2 Answers2

5

It's because what you're doing is undefined so the compiler is free to do what it wants. You are not permitted to change the value of a variable more than once without an intervening sequence point, the list of which can be found in Appendix C of C99 or C11.

Your expression CUBE(++x) evaluates to:

((++x)*(++x)*(++x))

The most likely reason why you're getting different results is that, with the x = 5 version, the compiler can evaluate the result at compile time and may well just give you machine code to print out the constant value it calculates.

With the data entry version, the calculation is most likely left to run time which may use a different method of calculation.

A solution is to not use macros for code, something I haven't done for a long time - I only use them for conditional compilation nowadays since code macros can be done as inline functions and constant macros can be done with enumerations.

In other words, use:

inline int cube (int r) { return r * r * r; }

That's not exactly like the code macro since inline is only a suggestion (and, of course, the function doesn't suffer from undefined behaviour) but I often don't find the inline suggestion that useful nowadays since the compilers are a lot smarter than they used to be regarding optimisation.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

Both will give you an undefined behaviour. Use proper functions. Like inline function for your cube, something like this:-

inline int cube(int z) 
{ 
 return z*z*z; 
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331