0

Hellow I am a beginner in coding who is learning pointer. this is a simple code of passing pointers
to functions but I am getting wrong input.

#include<iostream>
using namespace std;
void increment(int *a){
    *a++;
}
int main(){
    int a=2;
    //int *p=&a;
    increment(&a);
    cout<<a;
    return 0;
}

output is showing 2;

Chris
  • 26,361
  • 5
  • 21
  • 42
Toney 85
  • 1
  • 1

1 Answers1

2

What happened here? The C++ grammar effectively defines something we commonly refer to as "operator precedence" (since it's defined by the grammar, you won't find chapter in the C++ standard where the precedence would be listed in a convenient way, but there are websites that worked it out).

In *a++;, the pointer will be increased (a++) and thus pointing to an invalid position. After that, the invalid pointer will be dereferenced (* operator), causing undefined behavior (UB). If you're learning, you want to get familiar with undefined behavior, because anything can happen.

To fix it, use parentheses to specify precedence explicity: (*a)++;.

Maybe you want to learn about references instead? Don't use raw pointers and pointer arithmetic. Compare your code to this code:

#include<iostream>
using namespace std;
void increment(int& a){
    a++;
}
int main(){
    int a = 2;
    increment(a);
    cout << a;
    return 0;
}

Also: Why is "using namespace std;" considered bad practice?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222