I have following homework exercise from lecture "Variables, references and pointers":
Write the function zero (...) so that the following code works correctly: int x = 3; zero(x); cout << x << endl; // writes 0
This is my solution:
#include <iostream>
using namespace std;
void zero(int &);
int main(void) {
int x = 3;
zero(x);
cout << x << endl;
return 0;
}
void zero(int & num) {
num = 0;
}
What do you think about it?
1 Answer 1
This isn't too complicated, so there isn't that much to say. Your code is perfectly clear, but there are a couple things that could be improved.
using namespace std;
This is okay-ish for beginning programming classes, but using namespace std
should usually be avoided. See Why is "using namespace std" considered bad practice?
void zero(int &);
You could just not forward declare the function, and instead just define the function here. It's a little less code to write. It comes down to preference
int main(void) {
Don't use void
to say that a function takes no arguments. It's a C-ism, and should be avoided in C++. Just write int main() {
.
int main(void) { ... return 0; }
There's no need to have a return 0;
at the end of main()
. For the specific case of the main
function, return 0;
is implied at the end of the function.