New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
improvement proposal for json_object_object_foreach #475
Comments
That does not work the same, because the macro intends you to provide the body of the for loop right after it, like: json_object_object_foreach(fruitstand, fruit, q) {
printf("%s: %d\n", fruit, json_object_get_int(q));
} The body appearing after a I think this macro should work when nested, if you choose different names for |
The loops are not even nested, they are right behind each other. I use the first one to see how many entries in a table I need. After I know that I allocate some memory and use the 2nd loop to fill my new table up. If I would use nested loops, I think the renaming makes totally sense. The error messages look like this:
You are right, I guess the do { } while (0) does not work in this case. I had added it around the foreach blocks such that it created its own block. That way the scope of the variable definitions was separated and the warnings disappeared. I agree that renaming helps to overcome the problem, but I thought that it is much better read and understandable (also copy-paste works better ;-), if multiple of those loops use the same variable names. Now I tried this:
That works, but I wonder if I really improved it ;-). Maybe you have a nicer idea? |
Ah, I see, same problem when not nested. You can easily use different key and val names, they're macro args for this reason: foo();
json_object_object_foreach(jobj, key1, val1) {
bar(key1, bval1);
}
json_object_object_foreach(jobj, key2, val2) {
bar(key2, val2);
} If you really want to use the same key and val names, you can create a block scope without any control flow statements, like: foo();
{
json_object_object_foreach(json_obj, key, val) {
bar(key, val);
}
}
{
json_object_object_foreach(json_obj, key, val) {
bar(key, val);
}
} Subjectively, I think both these options are better than separate "start" and "end" macros. |
Thanks for the comments. I guess I get along so far. There is another thing I just found when carrying the code over to a Linux box with recent gcc. In my count loop I do not use the key variable. |
Problem has been solved and this issue could be closed @hawicz |
I tried to use the macro two times within one function and got warnings/errors due to double definitions of key and value. Looking at the current version:
it is obvious why this is. I think it would be good idea to wrap the block into a do { } while (0), which I think makes my problem go away:
What do you think?
The text was updated successfully, but these errors were encountered: