Addition With long integers crashes program

Hello!

i hope that someone hasn't posted something similar already, but I didn't find anything. I'm doing a project using a gyro and accelerometer and have run into an issue which crashes the program.

Below I posted some test code which highlights the problem.

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

  Serial.begin(57600);
  Serial.println("Calculation Test");

  Serial.println("Each for it self");
  long x,y,z;
  x=(381*381L);
  y=(long)387*387;
  z=(long)4145*4145;
  Serial.print(x);
  Serial.print("\t");
  Serial.print(y);
  Serial.print("\t");
  Serial.println(z);


  long tmp;
  tmp=(long)(145161+149769+17181025);     //Here is the problem!
  double total_acc;
  total_acc=sqrt(tmp);

  Serial.println(tmp);
  Serial.println(total_acc);
}

When I try add the the numbers together at the location marked in the code, the serial output only looks like the following.

Calculation Test

However if i comment out the that line, the output looks like it should (except of course that the two last calculations end up wrong).

Calculati⸮⸮⸮⸮⸮5
Each for it self
145161 149769 17181025
0
0.00

Why does not even the first calculations, that worked previously, show up? It just aborts after the first print?

I'm guessing something is wrong with the variable types. But this seems to work fine when i test doing the same thing in a regular C++ program.

Would appreciate help, thanks in advance!
/magal000

I'm guessing something with the variable type doesn't work here

Serial.begin usually goes in setup.

Fix that and retest.

yes here is your problem
[code]tmp=(long)(145161+149769+17181025); //Here is the problem![/code]
you only cast after the addition, so the calculation is not done as a long, what if you add

tmp=(x+y+z);

or

tmp=(145161+149769+17181025L);

and yes as in #1

AWOL:
Serial.begin usually goes in setup.

Fix that and retest.

Thanks! This seems to fix it. I don't know why I put it there

Deva_Rishi:
yes here is your problem
[code]tmp=(long)(145161+149769+17181025); //Here is the problem![/code]
you only cast after the addition, so the calculation is not done as a long, what if you add

tmp=(x+y+z);

or

tmp=(145161+149769+17181025L);

and yes as in #1

Ahh, another misstake!

Thank you all!