Simple if comparison won't work

While coding I got into this weird situation, where my code just wouldn't work as it should. I even made it in Visual Studio in C#, and there, the same logic worked just fine. After some testing, I got to this simple code, that don't work as it should. Test it and see it:

void setup() {
  Serial.begin(9600);
}

void loop() {
  int arr[] = {32768};

  if (1 > arr[0])
  {
    Serial.println("1 is greater than 32768");
  }
  else
  {
    Serial.println("1 is not greater");
  }
  delay(1000);
}

Any time I try to make a comparison with a value in an array bigger than 327698 (which is the maximum number for 2 bytes) things don't happen as they should.
Appreciate any enlightening.

Welcome

The max value of 2 bytes signed int is 32767 ( 2^15 - 1 )

try unsigned arr[] = {32768};

Got it:

It is an arduino limitation for some chips. Since I am using nano, int can't go further than 2 bytes.

Thank you.

It is actually not a limitation, just a choice made by the developers of Arduino, and specific to AVR based Arduinos.

The size of an int variable is not specified by the C/C++ programming language. If you want your program to operate as expected on other MCUs, determine the size of an int using the sizeof operator. For example:

int number_of_bytes_in_int = sizeof (int);

Or use stdint.h then you can code things like

uint16_t
int32_t
uint8_t
etc

then you know exactly what size you have.

I always thought that making the size of types to be processor dependent was a major design flaws in C.

1 Like

it's actually just a single bit.
the range of in is -32768 - 32767
the range if unsigned int is 0 - 65535
both int and unsigned int are 2 bytes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.