Cast

Hello, can somebody explain the difference between cast and conversion, please?

cast e.g. int x; float y; y = (float) x;

conversion e.g. int x; float y; y = float(x);

Thank you :slight_smile:

Hello, can somebody explain the difference between cast and conversion, please?

The "conversion" is creating a float from the value in the parentheses. Since you have not given x a value, you haven't a clue what will be in y.

The cast is telling the compiler to treat some number of bytes (4 in the case of a float cast) as though they were a float. The first byte is the first byte of the variable x. The second byte is the second half of x. The 3rd and 4th bytes are whatever bytes follow x in memory.

The result of that cast will be garbage in y, too.

Ok, thank you.
Can you give some examples where i have to use conversion and where i have to use cast, please?

PaulS:
The cast is telling the compiler to treat some number of bytes (4 in the case of a float cast) as though they were a float. The first byte is the first byte of the variable x. The second byte is the second half of x. The 3rd and 4th bytes are whatever bytes follow x in memory.

That is only true for pointers to float / int.

Functional there should be no difference in value between (float)x and float(x).

int x = 1234;

void setup() {
  Serial.begin(250000);
  float y = (float)x;
  Serial.print(F("(float)x      = "));
  Serial.println(y);
  y = float(x);
  Serial.print(F("float(x)      = "));
  Serial.println(y);
  y = *((float*)&x);
  Serial.print(F("*((float*)&x) = "));
  Serial.println(y);
}
void loop() {}
(float)x      = 1234.00
float(x)      = 1234.00
*((float*)&x) = 0.00

Can you give some examples where i have to use conversion and where i have to use cast, please?

You NEVER have to use "conversion".

float y = 1234;

does EXACTLY the same thing as

float y = float(1234);

You rarely need to cast one type to another, unless the types are pointers. When you DO need to cast, you'll know it, and know what cast is required.

Whandall:
Functional there should be no difference in value between (float)x and float(x).

Exactly!

void setup()
{
  Serial.begin(9600);
  int x = 1234;
  float y;
  y = (float)x;
  Serial.println(y); //shows: 1234.00

  long *p;
  p = (long*) &y;
  long m = *p;
  Serial.println(m, HEX); //shows: binary32 formatted value 449A4000

  Serial.println("//--------------------------------");
  float y1;
  y1 = float(x);
  Serial.println(y1); //shows: 1234.00

  long *p1;
  p1 = (long*) &y1;
  long m1 = *p1;
  Serial.println(m1, HEX); //shows: binary32 formatted value 449A4000
}

void loop()
{

}