Pointer vs. Reference

后端 未结 12 1713
闹比i
闹比i 2020-11-22 11:13

What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;

void func1(unsigned long& val) {
     val          


        
12条回答
  •  生来不讨喜
    2020-11-22 11:20

    Pointers

    • A pointer is a variable that holds a memory address.
    • A pointer declaration consists of a base type, an *, and the variable name.
    • A pointer can point to any number of variables in lifetime
    • A pointer that does not currently point to a valid memory location is given the value null (Which is zero)

      BaseType* ptrBaseType;
      BaseType objBaseType;
      ptrBaseType = &objBaseType;
      
    • The & is a unary operator that returns the memory address of its operand.

    • Dereferencing operator (*) is used to access the value stored in the variable which pointer points to.

         int nVar = 7;
         int* ptrVar = &nVar;
         int nVar2 = *ptrVar;
      

    Reference

    • A reference (&) is like an alias to an existing variable.

    • A reference (&) is like a constant pointer that is automatically dereferenced.

    • It is usually used for function argument lists and function return values.

    • A reference must be initialized when it is created.

    • Once a reference is initialized to an object, it cannot be changed to refer to another object.

    • You cannot have NULL references.

    • A const reference can refer to a const int. It is done with a temporary variable with value of the const

      int i = 3;    //integer declaration
      int * pi = &i;    //pi points to the integer i
      int& ri = i;    //ri is refers to integer i – creation of reference and initialization
      

提交回复
热议问题