Eka Eka - 4 months ago 8
C++ Question

Using if else statement with json values in jsoncpp

I am trying to do something similar using

jsoncpp
inside a function which returns json values as strings.

std::string some_function(std::string val){
.
.
.
if(val=="date")
{
Json::Value my=root["data"]["date"];
std::cout<<"Date";
}
else if(val=="id")
{
Json::Value my=root["data"]["id"];
std::cout<<"ID";
}
else if(val=="art")
{
Json::Value my=root["data"]["article"];
std::cout<<"Article";
}
else
{
return "Error";
}
//Json::Value my=root["data"]["date"]; //this works
return my.toStyledString();
}


I am able to successfully run json values example:
Json::Value my=root["data"]["date"];
outside the if else statement(comment out code) but when i tried to run these json values inside an if-else-if statment it shows this error


warning: control reaches end of non-void function [-Wreturn-type]

Answer

I guess that's not the only error you get, you should get errors that my isn't defined or declared anywhere too.

That's because you have many variables my but each is defined only in its own scope, and none declared in the function scope. Since there is no such variable you get a follow up variable because of the first error.

The solution is very simple: Declare one variable before the if-else if-else chain and use only plain assignment:

Json::Value my;

if(val=="date")
{
    my=root["data"]["date"];
    std::cout<<"Date";
}
...

On an unrelated note, that's not how I would write such a function. I would probably do something like

std::string some_function(std::string val)
{
    static std::string const valid_values[] = { "date", "id", "art" };

    if (std::any_of(std::begin(valid_values), std::end(valid_values),
                     [&](auto const& s)
                     {
                         return s == val;
                     }))
    {
        return root["data"][val];
    }

    return "Error";
}