Home > Back-end >  JSON output differs between gcc and MSVC
JSON output differs between gcc and MSVC

Time:12-22

The below code snippet is using nlohmann-json library. However the output differs between MSVC and GCC compilers (both compiled using -std=c 14).

MSVC outputs:

{"test":[]}

gcc outputs:

{"test":[[]]}

Code snippet:

#include "nlohmann/json.hpp"
#include <iostream>

int main() {
    nlohmann::json output;
    output["test"] = { nlohmann::json::array() };
    std::cout << output.dump() << std::endl;
    return 0;
}

The line output["test"] = { nlohmann::json::array() }; is triggering the difference in behavior. Removing the curly brackets around nlohmann::json::array() will align the behavior and always output {"test":[]}. It seems the initializer list { json::array() } is interpreted by GCC as: json::array({ json::array() }) for some reason.

Could this be a potential bug in the json library, in GCC/MSVC or is there another explanation?

CodePudding user response:

The nlohmann library has an already known issue with brace initialization and different compilers.
They mention this issue in the FAQ.

The workaround the library authors propose is to avoid brace initialization.

  • Related