Does order of parameters matter?

Does it make any difference which order the parameters to a function are set?

Some parameters are passed by reference, others by value. Is there some rule that says that you cannot have a value parameter after a reference parameter or vice versa?

Thanks
Nope, order does not matter.
No there is no set rule about the order of parameters, however you should strive to keep the number of parameters small. And you should also be consistent with the order throughout your program. By consistent I mean that if your passing the "same" variables your functions then you should try to pass these variables in the same order regardless of how they are being passed.
1
2
3
int function1(int row, int col);
int function2(int &row, int col);
int function3(int row, int &col);


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.
Last edited on
Topic archived. No new replies allowed.