Unexpected Multiplication result from function

56 views Asked by At

I am working on a piece of code that calls a function and passes a number < 2 ** 16. The function only returns the number * 1000:

#pragma GCC optimize("Os") 

unsigned long getVal(unsigned short val) {
    return val * 1000 ;
}

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

void loop() {
    Serial.println(getVal(200)) ;
}

Now, if I send 200 to getVal(), I should get 200000, but it returns 3392! But if I modify the function like this:

unsigned long getVal(unsigned short val) {
    return val * 1000000 ;
}

I get 200000000 back, which is expected.

I can't literally multiply numbers with 1000, but 100,000 works just fine.

I already tried disabling the Optimization with O0, which doesn't fix the problem either.

I am not getting what's going on. I am on Arduino Nano.

1

There are 1 answers

0
datafiddler On BEST ANSWER

val * 1000000 performs a long multiplication, because one of the terms (1000000) is a long

val * 1000 does an int multiplication, because both terms are int. Arduino Nano int is 16 bit wide only, so the result is truncated before it is turned into the desired long return value.

unsigned long getVal(unsigned short val) {
    return val * 1000UL ;
}

is what you are looking for.