Is there any fathomable reason why we need void functions?
For the same reason that int main()
is a standard, why not simply return 0
from a function that doesn't require a return value? I see three immediate advantages to using an int
type:
1. We can return a code to indicate function status; typically, if there's a problem, we can return a non-zero error code.
2. We can output the return value of the function when debugging
3. It's the standard for the main() routine; that is, int main() {}
. Why not follow suit?
Is there any reason why we'd prefer void
over int
?
Example: A function that sorts an array of cheeses, and returns it by reference.
#include <iostream>
#include <string.h>
int sortArrayInt(string & _cheese[]) { // pun intended ;D
int errCode = 0;
try {
// ..sort cheese[] array
} catch(e) {
errCode = 1;
}
return errCode;
}
void sortArrayVoid(string & _cheese[]) {
// .. sort cheese[] array
// no return code to work with, doesn't follow int main() standard, and nothing to output.
}
int main() {
string cheese[5] = {"colby","swiss","cheddar","gouda","brie"};
std::cout << "Sort Status: " << sortCheeseArrayInt(cheese) << std::endl;
sortArrayVoid(cheese);
// ..print cheese array
}
OUTPUT:
Sort Status: 0
brie, cheddar, colby, gouda, swiss
Aucun commentaire:
Enregistrer un commentaire