Search code examples
c++operators

What does standalone operator * do at beginning of an equation in C++?


I'm going through some code and came across a line like:

x = * y

What is the asterisk (*) in this case? I have some programming knowledge, but I'm new to C++. I think I grasp the concept of pointer variables, but the order and spaces make me think it's different than the *= operator or *y pointer.


Solution

  • In x = * y, y is most likely a pointer to something, in which case * is used to dereference the pointer, giving you a reference to the object to which y points and x = *y; copy assigns that value to x.

    Example:

    int val = 10;
    int* y = &val; // y is now pointing at val
    int x;
    
    x = *y;        // the space after `*` doesn't matter
    

    After this, x has the value 10.

    Another option is that y is an instance of a type for which operator* is overloaded. Example:

    struct foo {
        int operator*() const { return 123; }
    };
    
    int main() {
        foo y;
        int x;
        x = *y;
    }
    

    Here, *y calls the operator*() member function on the foo instance y which returns 123, which is what gets assigned to x.


    the order and spaces make me think it's different than the *= operator or *y pointer.

    The spaces don't matter. * y and *y are the same thing, but it is indeed different from *=, which is the multiply and assign operator. Example:

    int x = 2;
    int y = 3;
    x *= y;     // logically the same as `x = x * y;`
    

    After this, x would be 6.


    Combining dereferencing and the mutiply and assign operator while using a non-idiomatic placement of spaces can certainly produce some confusing looking code:

    int val = 10;
    int* y = &val;
    int x = 2;
    
    x *=* y;     // `x = x * (*y)`  =>  `x = 2 * 10`