c++ - New to pointers, what's the difference between these? -
this question has answer here:
both of these functions rewrites original value right? there benefit doing 1 way on other?
#include <iostream> using namespace std; void passptr(int *p) { *p = 7; } void passaddy(int &a) { = 7; } int main() { int = 5; int *p = &a; passptr(p); cout << << endl; = 5; passaddy(a); cout << << endl; return 0; }
in case, references superior because cannot make common mistakes of pointers--references must point type of object reference, , cannot ever null or nullptr, automatically eliminates many of headaches of dealing pointers.
some compilers can use pointers implement references, 2 have different semantics. these semantics useful in different cases. here, it's easier not have remember dereference pointer--it's pesky layer of abstraction won't trip on when code. in other cases, might favourable able have null pointer or reference.
Comments
Post a Comment