Home > Software engineering >  Change Nlohmann json key-value with increment function? c
Change Nlohmann json key-value with increment function? c

Time:09-01

Instead of this:

j["skills"]["atk"] = j["skills"]["atk"].get<int>()   6;

I want something like this:

void json_inc(json ref, int value) //function to increment int key-values
{
    ref = ref.get<int>()   value;
}

json_inc(j["skills"]["atk"], 6); //adds 6

Is this possible for nested json objects like above?

CodePudding user response:

You are passing your json object by value. This means, that the object will, in fact, be duplicated in memory and whatever changes you make to the object will ceased to exist once you leave the scope of the function.

To actually manipulate the variable you are passing (and this works for any kind of C variable), you need to pass by reference.

This is done by changing the prototype of your function to void json_inc(json &ref, int value).

The & operator means 'reference' in C . Under the hood, this reference is an immutable pointer to the variable you are passing, performing any changes you do directly on the variable you are passing instead of a copy.

For larger structures, it is just about almost desirable to pass by reference, because it eliminates the need to copy the object on the stack (after all, only the original variable needs to exist).

If you should venture into C at some point (where references do not exist), you can achieve the same thing with pointers:

void json_inc(json *ref, int value) //function to increment int key-values
{
    *ref = ref->get<int>()   value;
}

json_inc(&j["skills"]["atk"], 6); //adds 6
  • Related