esp8266 / Arduino

ESP8266 core for Arduino
GNU Lesser General Public License v2.1
16.06k stars 13.33k forks source link

Integer variable overflow - different behaviour between Uno and ESP8266 #2017

Closed ghost closed 8 years ago

ghost commented 8 years ago

Basic Infos

Same program, designed to demonstrate overflow of integer variable during calculation, gives different results on Arduino UNO and nodeMCU 0.9.

Hardware

Hardware: nodeMCU 0.9 Core Version: 2.2.0

Description

The attached program is intended to show how calculations where intermediate results exceed the size of the result variable will cause overflow and unexpected results.

On the Arduino Uno, the program output is:

x = 27
y = 27
z = 27

On the nodeMCU, the output is:

x = 27
y = 1626
z = 1626

In the second and third calculations, the intermediate value of 200,000 is not overflowing.

Settings in IDE

Module: NodeMCU 0.9 (ESP-12 module) Flash Size: 4M (3M SPIFFS) CPU Frequency: 80Mhz

Sketch

void setup()
{
  delay(1000);
  Serial.begin(115200);
  Serial.println("\n\n");

  int16_t w, x, y, z;

  w = 200 * 1000;
  x = w / 123;

  Serial.print("x = ");
  Serial.println(x);

  y = 200 * 1000 / 123;

  Serial.print("y = ");
  Serial.println(y);

  z = (200 * 1000) / 123;

  Serial.print("z = ");
  Serial.println(z);

}

void loop()
{

}
igrr commented 8 years ago

What is the unexpected thing here? Int size on AVR is 16 bit, while on ESP it is 32 bit.

Makuna commented 6 years ago

don't use int, use the newer int8_t, int16_t, int32_t, int64_t types instead.