Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ passing arguments by reference and pointer

in c++

class bar {     int i;     char b;     float d; };  void foo ( bar arg ); void foo ( bar &arg ); void foo ( bar *arg ); 

this is a sample class/struct and functions
i have some Qs

  • what's the difference between 1st and 2nd way of passing the argument in 'asm', size, speed ?
  • how the arguments are passed to the functions foo in each case ( in case of pointer i know the pointer is pushed on the stack )
  • when passing arguments, in terms of efficiency at ( speed, size, preferability ) which is better ?
  • what's the intel 'asm' syntax that corresponds each of the ways of passing arguments ?

i know what most say about "it doesn't matter on modern compilers and CPUs" but what if we're talking about Old CPUs or compilers?

thanks in advance

like image 250
VirusEcks Avatar asked Jul 18 '11 12:07

VirusEcks


People also ask

Can you pass arguments by reference in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

Are pointers passed by reference or value in C?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

Does pass-by-reference use pointers?

The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.

Why are pointers used in passing parameters by reference?

In C++, variables are passed by reference due to following reasons: 1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function.


1 Answers

The pointer and the reference methods should be quite comparable (both in speed, memory usage and generated code).

Passing a class directly forces the compiler to duplicate memory and put a copy of the bar object on the stack. What's worse, in C++ there are all sort of nasty bits (the default copy constructor and whatnot) associated with this.

In C I always use (possibly const) pointers. In C++ you should likely use references.

like image 78
cnicutar Avatar answered Oct 03 '22 02:10

cnicutar