Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax explanation with pointers as function parameters (C++)

Tags:

c++

syntax

I'm not sure if I can ask basic questions here, but I am starting to learn C++ and do not understand one little thing in pointers syntax.

Here is the sample of my code:

using namespace std;

int randomname(int *x);

int main(){

    int a = 1;

    int *ab;

    ab = &a;

    randomname(&a);

}


int randomname(int *x){

    *x = 9001;

}

My question is about the * symbol. Why in the main function on line ab = &a; I don't need the *, but on line *x = 9001; I need it? I think syntax should be same in both functions, but it isn't. Can someone please explain why?


1 Answers

The meaning of both the asterisk * and the ampersand & changes depending on the context. Their meanings in expressions and in declarations are different:

  • When * is used in a declaration, it designates a pointer
  • When & is used in a declaration, it designates a reference
  • When * is used in an expression, it performs a pointer dereference of its operand
  • When & is used in an expression, it obtains a pointer of its operand

Once you understand these distinctions, you can tell that

  1. Line int *ab is a declaration. Asterisk designates ab as a pointer.
  2. Line ab = &a; has an expression. & takes a's pointer, and assigns it to ab, which has a pointer type specified at the time of its declaration (above).
  3. Line *x = 9001 is also an expression, making the asterisk a dereference operator. You use the asterisk to tell the compiler that the target of the assignment is whatever is pointed to by x, not x itself.
like image 191
Sergey Kalinichenko Avatar answered Sep 28 '26 04:09

Sergey Kalinichenko