Arduino: Integer variable overflow - different behaviour between Uno and ESP8266

Created on 11 May 2016  路  2Comments  路  Source: esp8266/Arduino

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()
{

}

Most helpful comment

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

All 2 comments

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

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

Was this page helpful?
0 / 5 - 0 ratings