Pointer Reference Increment

#include <iostream>
using namespace std;

// Define incrementPtr(int* x)
// Increment the value pointed to by x
// Do nothing if x is nullptr

// Define incrementRef(int& x)
// Increment the referenced value
void incrementPtr(int* a){
      if(a != nullptr) {
        (*a)++; 
    }
}
void incrementRef(int &b){
     b++;
}

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

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

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

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6