When to use references vs. pointers

前端 未结 17 2143
一向
一向 2020-11-22 02:27

I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:10

    Points to keep in mind:

    1. Pointers can be NULL, references cannot be NULL.

    2. References are easier to use, const can be used for a reference when we don't want to change value and just need a reference in a function.

    3. Pointer used with a * while references used with a &.

    4. Use pointers when pointer arithmetic operation are required.

    5. You can have pointers to a void type int a=5; void *p = &a; but cannot have a reference to a void type.

    Pointer Vs Reference

    void fun(int *a)
    {
        cout<

    Verdict when to use what

    Pointer: For array, linklist, tree implementations and pointer arithmetic.

    Reference: In function parameters and return types.

提交回复
热议问题