When to use * and &

This is a discussion on When to use * and & within the C++ Programming forums, part of the General Programming Boards category; I come from a Java background, where EVERYTHING is a pointer, I've been having some trouble getting my head around ...

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    11

    When to use * and &

    I come from a Java background, where EVERYTHING is a pointer, I've been having some trouble getting my head around * and & in c++. It's not easy to google this sort of thing because I'm pretty sure google ignores special characters.

    I know & is along the lines of "reference of" and * is along the lines of "pointer", I'm still not sure in which situation I should be using a & or *, I've tried swapping them out and I get near the same results. In the small mini game I've been working on to learn c++ I've mostly been using * all around to designate that I want to use a pointer, and not create copies of the object, I just want to store the pointer in a different variable, but looking at sample code I've found on the internet it seems I am doing it incorrectly.

    I would appreciate it if someone could either post me to a good article that talks about & and *, or at least maybe give me a quick run down on what the purpose of these operators are exactly

    When I talk about these sort of assignments I mean stuff like

    MyClass* varname;
    MyClass& varname;

    btw is there a difference between defining with
    MyClass* varname
    versus
    MyClass *varname;

    (looking at the location of the *).


    edit: btw when I say that I see "sample code" using & where I would use * I mean like on this page
    http://www.cplusplus.com/reference/stl/vector/vector/

    the parameters use &, in my own code I have been using *, but achieving the effect that I desire (or at least I think I am), I am thinking there is some difference in the details that will come back and hurt my down the road.


    thanks
    Last edited by misterdanny; 08-01-2009 at 01:02 AM.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    btw is there a difference between defining with
    No, they are the same.

    References and pointers perform a similar function in C++. In fact, you can usually get by with just using one or the other. References are nice because they guarantee that there is an underlying object. Pointers can technically point at anything, so there is more room for error. A good rule for C++ is to use references everywhere you can, and only use pointers when you have to.

    Take a look at this:
    Code:
    void foo(int* i)
    {
        *i = 5;
    }
    void bar(int& i)
    {
        i = 5;
    }
    
    int main(void)
    {
        int i = 0;
        foo(&i); // this works
        bar(i); // this works too
        foo(NULL); // now we crash.  Using pointers opens us up for this type of error.
    }
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    HelpingYouHelpUsHelpUsAll
    Join Date
    Dec 2007
    Location
    In your nightmares
    Posts
    223
    Quote Originally Posted by misterdanny View Post
    btw is there a difference between defining with
    MyClass* varname
    versus
    MyClass *varname;
    To the compiler, these mean exactly the same, although they read differently (IMO). You probably should be consistant with which one you use, I prefer the latter because that is what I have gotten used to.

    Code:
    I know & is along the lines of "reference of" and * is along the lines of "pointer", I'm still not sure in which situation I should be using a & or *
    The '&' does mean reference of and I think of it for getting the address of a variable (like where you pass values "by reference" (bar() in bithub's previous post) you pass the address of where the variable is in memory. I think of the * as get the value that is located in this address (note pointers are variables that hold an address). That is how I think of them anyway, though I could be wrong. That seems to be consistant with how I have used them in my (not so long experience w/ C++ (I have more exp w/ C) so C++'s method of "passing by reference" is farily new to me, I would have done the same passing a pointer then placing an * in front of nearly every time that var is used in the function. Often you will find that there are two methods of doing things involving '&' & '*' (like the passing by reference I mentioned earlier). Hope that helps.
    long time no C; //seige
    You miss 100% of the people you don't C;
    Code:
    if (language != LANG_C && language != LANG_CPP)
        drown(language);

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    Pointer way (3 steps):
    1) Define a pointer (put a * somewhere between the type and the name).
    2) Make the pointer point to something by assigning it an address. An address can be acquired with the address of (&) operator.
    3) Do something with the value the pointer points to. Get the value the pointer points to by using *, the dereference operator.
    A pointer is just a variable, so if you don't dereference it, you assign a value to the pointer itself, not the value it points to; and a pointer's value must be a valid address.

    The reference way (1 step):
    1) Define a reference (put & somewhere between the type and the name).
    Non-existant 2) Use as a normal variable.
    A reference is merely an "alias" for an existing variable, so everything you do to the reference will happen to the "aliased" variable.
    What separates references from pointers mostly is that they cannot be NULL. They MUST point to a valid destination. That is why it is best to use references when you want to ensure this.
    Note that references MUST be initialized; they cannot be reassigned later on. For these situations, pointers take over.

    This combined with the example should help.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Jan 2007
    Posts
    11
    So is there a difference between

    Code:
    int x = 5;
    
    int* z= x;
    verus


    Code:
    int x = 5;
    
    int* z= &x;

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by misterdanny View Post
    So is there a difference between

    Code:
    int x = 5;
    
    int* z= x;
    verus


    Code:
    int x = 5;
    
    int* z= &x;
    Mainly, in that the second one is right and the first one is extremely extremely wrong. (The first one sets z to point at the memory address 0x05 which is pretty much guaranteed to not be yours. The second one sets z to point at the memory address where x lives.)

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,411
    The first will generate a compile error and the second will work. Why?
    Because the pointer stores a memory address - it points to something. That doesn't mean you can just assign an integer to it, which is not a memory address.
    You need to assign a memory address, and a memory address is ALWAYS a pointer (&x in your example is int*; while x is int).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21