-10

I am beginner in c++ programing I got this question in my university exams and have no idea why the output is like that, the question goes like this What is the output of the following code?

#define SQUARE(x) x*x
inline float square(float y){
  return y*y;
}
void main( ){
  float a = 0.5,b = 0.5, c, d; 
  c = SQUARE(++a);
  d = square(++b);
}

The question itself does not have any cin or cout statement to display any output in the console screen so here is altered code

#include<iostream>
#define SQUARE(x)x*x
using namespace std;
inline float square(float y){
  return y*y;
}
int main(){
  float a = 0.5,b=0.5,c,d;
  c=SQUARE(++a);
  d = square(++b);
  cout<<c<<endl<<d;
}

And the output for the above code is 6.25 2.25 why the output isn't is 2.25 and 2.25 instead it is 6.25 and 1.25?

unkown
  • 1
  • 1
  • 2
    macros `define` is just string replacement before compilation, so actual code is `c=++a * ++a;` – Iłya Bursov Jun 11 '23 at 12:54
  • Why would you expect console output, for never outputting anything?? – πάντα ῥεῖ Jun 11 '23 at 12:54
  • 1
    Do you know what `#define` does? If not, I would go read a C++ tutorial. They reason they produce different values is they do *very* different things. If they did the same thing, you would not have both `#define` and regular functions in the same language. – user229044 Jun 11 '23 at 12:55
  • 3
    _"I tried asking chat gpt as well but it does not give me quite clear explanation."_ I have no idea why you should expect something there? You do know what ChatGPT actually is?? – πάντα ῥεῖ Jun 11 '23 at 12:56
  • There is a reason macros are not recommended. Whenever you can you should use a (template) function. – Pepijn Kramer Jun 11 '23 at 13:08
  • 1
    Change `#define SQUARE(x)x*x` to `#define SQUARE(x) [](auto xx){ return xx*xx; }(x)` and the problem will be solved. – Eljay Jun 11 '23 at 15:01
  • I like macros: SQUARE("circle"). If this were an inline function, you'd get an error early on. – Thomas Matthews Jun 11 '23 at 18:54

1 Answers1

0

On preprocessing, the macros (created using #define) are replaced with the expressions they define.

  • SQUARE(1+2) becomes 1+2*1+2 which is not what you want.
  • SQUARE(++a) becomes ++a*++a which is also not what you want.

The first situation can be solved by using parentheses in the definition of SQUARE:

#define SQUARE(x) ((x)*(x))

The second cannot be solved but there are alternatives:

  • separate the increment from the usage of SQUARE():
    a++;
    c = SQUARE(a)`;
    
  • transform SQUARE() into a function then you can use it as SQUARE(++a) to get the desired outcome.
axiac
  • 68,258
  • 9
  • 99
  • 134