Search code examples
c++pointersreferencedereference

C++ beginner question: dereference vs multiply


Just getting into C++. I'm getting constantly thrown off track when I see the symbol for multiply (*) being used to denote the dereferencing of a variable

for example: unsigned char * pixels = vidgrabber.getPixels();

Does this throw other people off? What's the tip for getting my head around this?

Thank you.


p.s. I have another reasonably simple question, that didn't get answered :( here: beginner question: add/subtract to value rather than just be that value pretty please! and thanks for your time!


Solution

  • C, and by inheritance C++, are swamped with operators and are inherently context-sensitive. You will have to get used to it:

    If * appears before the name of a variable that is being declared (or defined), it's a type modifier and makes that variable a pointer.
    If it is a unary prefix operator for a variable that is part of an expression, it's dereferencing (or whatever it's been overloaded to).
    If it is a binary infix operator for two variables that are part of an expression, it's multiplication (or whatever it's been overloaded to).

    (From this you can see that the * in your unsigned char * pixel isn't a dereferencing unary prefix, but a type modifier.)

    Note that & pretty much resembles *, only it's meaning is different: it makes a variable a reference, is the address-of operator, or the binary AND.