Pointer Reference Increment

#include <iostream>

void incrementPtr(int *x){
    if(x != nullptr){
        (*x)++;   // dereferance first and then increment (considering a operator presedance)
    }
}

void incrementRef(int& x){
    x++;
}

int main() {
    int n;
    std::cin >> n;

    int a = n;
    incrementPtr(&a);
    std::cout << "After incrementPtr: " << a << "\n";

    int b = n;
    incrementRef(b);
    std::cout << "After incrementRef: " << b;

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6