What's the difference between using * and using & in C++ functions? -


i trying find out using below code sort array in asscending order. , find method 1,2,3,4 same result:1234.

which method best?

and when , why should should use pointer /reference? you.

  1. using & call, , * in function parameter

  2. just used * in function parameter

enter image description here

  1. just used & in function parameter

    enter image description here

  2. nothing:

    #include <iostream> using namespace std;   void swap(int a,int b){      int t;     t=a;     a=b;     b=t; } void main(){      int a[]={1,2,3,4};     (int i=1; i<3; i++)         (int j=3; j>i;j--)             if(a[j]<a[j-1])                 swap(a[j],a[j-1]);       cout << a[0] <<a[1]<<a[2]<<a[3]; } 

your first 2 versions identical. both explicitly pass pointer in function.

your third version has same semantics, different syntax. references can seen pointers nicer syntax.

your fourth version doesn't swap variables pass in because pass value, copied.

i prefer third version clearer.


Comments