#define directive & maths

I am exploring the use of the #define directive in c++. I am aware that it has some maths capability however I have found something that at first glance seems inconsistent.

The following produces expected results:
#define a 1.5
#define ax a * 2

However the following produces an unexpected result for c*2
#define a 1.5
#define b 2.3
#define c a + b
#define cx c * 2

The result is expected to be 7.6 not 6.1

Could someone please explain to a new c++ user what is happening here?

The output of my sample code is:
a = 1.500000 Correct
a2 = 3.000000 Correct
c = 3.800000 Correct
c
2 = 6.100000 Error
sqrt(c) = 1.949359 Correct
log10(c) = 0.579784 Correct

// Define_ERR.ino
// Pre-process of input data

#define a 1.5
#define b 2.3

#define ax a * 2.0

#define c a + b

#define cx c * 2.0
#define cs sqrt(c)
#define cl log10(c)


void setup() {
  Serial.begin(9600); 
  
  Serial.print("a = ");
  Serial.print(a, 6);
  Serial.println(" Correct");
  Serial.print("a*2 = ");
  Serial.print(ax, 6);
  Serial.println(" Correct");
  Serial.print("c = ");
  Serial.print(c, 6);  
  Serial.println(" Correct");
  Serial.print("c*2 = ");
  Serial.print(cx, 6);
  Serial.println(" Error");
  Serial.print("sqrt(c) = ");
  Serial.print(cs, 6);
  Serial.println(" Correct");
  Serial.print("log10(c) = ");
  Serial.print(cl, 6);
  Serial.println(" Correct");

}

void loop() {

}

You should use parentheses in your macro definitions, e.g.

#define a 1.5
#define b 2.3
#define c (a + b)
#define cx (c * 2)

Macros just replace text in code, so if you do that manually yourself, it'll be evident why the parentheses are required and why you get the wrong results.

#define does not do math. It does literal string substitution, and the math is performed by the compiler. You need to use parentheses to ensure the expressions are evaluated as you intend. Right now you have, effectively:

c = a + b
cx = a + b * 2

This is NOT what you intend....

Regards,
Ray L.

Thanks guys.
What an incredibly swift response

Just a follow on: If I don’t use the variables a and b in my programming except in the #define directives do they result in any memory allocation in the compiled code. (apart from the derived variables c and cx etc that are used in the body of the program)

No, macros don't allocate memory themselves (they are used by preprocessor for text substitutions). It depends how you use the macros in the code if they cause memory allocation (and which memory allocation if so).