I am having a hard time figuring out why I need to add the "if (addition) {}". In other words, if I run the code by simply writing, "*addition = x + y;", it crashes.
Also, why doesn't addition1 have to be declared as a pointer? I thought I needed a pointer to pass through a function that accepts a pointer as an argument.
Thank you so much for your help!
1 2 3 4 5 6 7 8 9 10 11 12 13
int functionPtr(int x, int y, int* addition) {
if (addition) {
*addition = x + y;
}
return x * y;
}
main(){
int x = 1;
int y = 2;
int addition1 = 0;
int multi = functionPtr(x, y, &addition1);
}
I am having a hard time figuring out why I need to add the "if (addition) {}".
When the function is called it is possible to pass a null pointer as the third argument functionPtr(x, y, nullptr);. A null pointer means the pointer is not actually pointing to any object so trying to write to the object pointed to by the pointer is not allowed, and that's why you use an if statement to check if the pointer is not null.
In other words, if I run the code by simply writing, "*addition = x + y;", it crashes.
In the code you have posted it should not crash even if you remove the if statement because the addition pointer is valid and points to addition1 in the main function.
Also, why doesn't addition1 have to be declared as a pointer? I thought I needed a pointer to pass through a function that accepts a pointer as an argument.
& is the address-of operator, it gives you a pointer to the object. &addition1 gives you a pointer to addition1.
Runs fine in C++ Shell (click the little gear button!)
Andy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream> // added output
int functionPtr(int x, int y, int* addition) { // char after y was not a comma
//if (addition) {
*addition = x + y;
//}
return x * y;
}
int main(){ // added teturn type (so C++ conformant)
int x = 1;
int y = 2;
int addition1 = 0;
int multi = functionPtr(x, y, &addition1);
std::cout << "multi = " << multi << "\n"; // added output
std::cout << "addition1 = " << addition1 << "\n"; // added output
return 0; // added as I'm pedantic
}