-2

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]

Eka
  • 14,170
  • 38
  • 128
  • 212
  • 1
    *warning: control reaches end of non-void function [-Wreturn-type]* implies your function has a path that does not return. Can you past a actual [mcve]? – NathanOliver Aug 02 '16 at 16:37
  • 1
    This way `my` doesn't exist when you exit `if/else` statements. Try to add `Json::Value my;` before `if/else` and then just `my=root["data"]["article"];`, etc – DimChtz Aug 02 '16 at 16:37

1 Answers1

3

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";
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621