Search code examples
c++mathwebassemblyemscripten

Why am I getting different integer results for emscripten and native code?


On a native build, the following code prints -1. Compiled to WASM and run in node.js, it prints 4294967295. Why are the results different?

#include <iostream>

int main() {
    unsigned F = 20;
    long HB = 19; // both give -1 if this is `long long`
    std::cout << HB-F << std::endl;
    return 0;
}

This is with g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 as the native compiler and em++ 3.1.66 (1f519517284660f4b31ef9b7f921bf6ba66c4041) for emscripten to compile to WASM.


Solution

  • sizeof(unsigned) == sizeof(long) in WASM like in Windows ABI, and long HB (that has the same size as int) is promoted to unsigned long (which on this platform has the same size as unsigned int).

    g++ by default translates the code to a 64-bit binary. In this case sizeof(unsigned) < sizeof(long) and unsigned F is promoted to long int.

    Try to invoke g++ with -m32 to get the WASM result.