You may pass parameters in any order you like.
However, there is one situation in which you're practically bound to pass parameters in a specific way, namely when you're dealing with default arguments.
Let's say you've got the following function:
1 2 3
|
void set_attributes(int health = 100, int armor = 50) {
//...
}
|
And you attempt to call it like this:
1 2 3
|
//I only want to set the armor!
int armor = 100;
set_attributes(armor);
|
This is an obvious mistake. The compiler won't generate an error, but the code isn't doing what you intended. How can the compiler possibly know which of the arguments you meant to set?
For this reason, if your function has more than one default argument, it's smart to have them appear in the order in which they will most likely need to be explicitly changed - from most likely to least likely:
1 2 3 4 5 6 7 8 9 10
|
#include <string>
struct Student {
std::string name;
std::string major;
};
Student create_student(std::string name = "John Doe", std::string major = "Computer Science") {
return Student{ name, major };
}
|
In this example, I've elected to have the name be the first default argument, and the major the second - it's more likely that students will have different names than different majors.