redundant initialization vs readability

If I have a function that I am to call 100 times in the life of a program, when should the variables be initialized? Is it better to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <vector>

std::vector<int>doStuff(unsigned long long& a, unsigned long long& b, std::string& got, std::vector<int> troubles);

int main() {
	std::vector<int>troubles = { 2314, 53256, 99573, 11245 };
	{
		unsigned long long a;
		unsigned long long b;
		std::string got;

		int iterator = 0;
		while (iterator < 100) {
			doStuff(a, b, got, troubles);
			iterator++;
		}
	}
}

std::vector<int>doStuff(unsigned long long& a, unsigned long long& b, std::string& got, std::vector<int> troubles) {
	a = 586309668549864;
	b = 2387638768467096;
	got = "lofty carrots";

	// do stuff

	return troubles;
}

or something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>

std::vector<int>doStuff(std::vector<int> troubles);

int main() {
	std::vector<int>troubles = { 2314, 53256, 99573, 11245 };
	
	int iterator = 0;
	while (iterator < 100) {
		doStuff(a, b, got, troubles);
		iterator++;
}

std::vector<int>doStuff(std::vector<int> troubles) {
	unsigned long long a = 586309668549864;
	unsigned long long b = 2387638768467096;
	std::string got = "lofty carrots";

	// do stuff

	return troubles;
}


I guess I am asking if it is generally better to write a function that unnecessarily initializes a set of variables over and over again in order to write more readable code.
Last edited on
I'd be more worried about continually copying that vector than merely initializing a couple of POD type variables.

But really where you "initialize" the variables should be determined by the purpose of the variables. You should define and initialize your variables close to first use. You will probably find that defining and initializing the variables in the function won't be much more expensive than continually passing the variables to the function. And don't forget if the variables are constants const qualify them.

Last edited on
Topic archived. No new replies allowed.