Pointer Reference Increment

#include <iostream>

// Define incrementPtr(int* x)
// Increment the value pointed to by x
// Do nothing if x is nullptr
void incrementPtr(int* x) {
    if (x == nullptr) {
        return;
    }
    ++(*x);
}

// Define incrementRef(int& x)
// Increment the referenced value
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

for the function taking pointer to value, check if the pointer has nullptr which implies it points to nothing and hence just return,  if not, deref the pointer and pre-increment the value.

References cannot be empty implying null check is not needed and reference variables can be directly operated on and dont need dereferencing, hence direct pre-increment

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6