Using names arguments on function call allows the developer to understand code more easily. It seems like it's not widespread in C++. Is it?
First, I want to show you examples of what I mean.
In Python, we can use keyword arguments like this
def f(x, y):
return x + y
f(x=1, y=2)
In JS we have a destructuring
function f({x, y})
{
return x + y;
}
f({x: 1, y: 2})
In C++20 there is a feature called designated initializers. These can be used to write names of parameters explicitly, though there is a problem: anonymous structures cannot be used as a parameter type like this
int f(struct { int x; int y; } args)
{
return args.x + args.y;
}
f({.x = 1, .y = 2});
So, I should use
struct f
{
int x;
int y;
};
int f(struct f args)
{
return args.x + args.y;
}
f({.x = 1, .y = 2});
I can use a union to systemize arguments usage for functions in a file
union Arguments
{
struct f
{
int x;
int y;
};
};
int f(struct Arguments::f args)
{
return args.x + args.y;
}
f({.x = 1, .y = 2});
Is the code like this okay, or it's better to not use names and remember signatures of all functions?
With plain function arguments it is a compiler error if you don't provide an initializer for a function parameter. Whereas with aggregate initialization the missing members are value-initialized. So, these two methods of passing function arguments are not equivalent with regards to compile time checking whether all function arguments are explicitly provided.
Also, individual function arguments are more likely to be passed in registers, whereas only structures of small size can be passed in registers. In other words, packing function arguments into a structure can make calls less efficient.