C++: Argument Passing "Passed by Reference"

Passing by reference in C

Because you're passing the value of the pointer to the method and then dereferencing it to get the integer that is pointed to.

C++: Argument Passing passed by reference

The ability to pass by reference exists for two reasons:

  1. To modify the value of the function arguments
  2. To avoid make copies of an object for performance reasons

Example for modifying the argument

void get5and6(int *f, int *s)  // using pointers
{
*f = 5;
*s = 6;
}

this can be used as:

int f = 0, s = 0;
get5and6(&f,&s); // f & s will now be 5 & 6

OR

void get5and6(int &f, int &s)  // using references
{
f = 5;
s = 6;
}

this can be used as:

int f = 0, s = 0;
get5and6(f,s); // f & s will now be 5 & 6

When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.

For eg:

void SaveGame(GameState& gameState)
{
gameState.update();
gameState.saveToFile("save.sav");
}

GameState gs;
SaveGame(gs)

OR

void SaveGame(GameState* gameState)
{
gameState->update();
gameState->saveToFile("save.sav");
}

GameState gs;
SaveGame(&gs);


Since only the address is being passed, the value of the variable (which could be really huge for huge objects) doesn't need to be copied. So passing by reference improves performance especially when:

  1. The object passed to the function is huge (I would use the pointer variant here so that the caller knows the function might modify the value of the variable)
  2. The function could be called many times (eg. in a loop)

Also, read on const references. When it's used, the argument cannot be modified in the function.

Does C even have pass by reference?

C parameters are always passed by value rather than by reference. However, if you think of the address of an object as being a reference to that object then you can pass that reference by value. For example:

void foo(int *x)
{
*x = 666;
}

You ask in a comment:

So why do we need pointers in C when we can pass all the parameters by value?

Because in a language that only supports pass-by-value, lack of pointers would be limiting. It would mean that you could not write a function like this:

void swap(int *a, int *b)
{
int temp = *a;
*b = *a;
*a = temp;
}

In Java for example, it is not possible to write that function because it only has pass-by-value and has no pointers.

In C++ you would write the function using references like this:

void swap(int &a, int &b)
{
int temp = a;
b = a;
a = temp;
}

And similarly in C#:

void swap(ref int a, ref int b)
{
int temp = a;
b = a;
a = temp;
}

C intro - How to pass a parameter by reference in function?

  1. It is perfectly valid. You can initialize and pass any number of pointer variables with their reference.

  2. This is also valid..when you pass the variable address, you should store it into a pointers

you have to do some changes in your code,
You can assign directly a/b and a*b pointer variables *c & *d
Then you have to read double number with %lf format argument.

#include <stdio.h>
#include <string.h>

void myFunction(double a, double b, double *c, double *d)
{
*c = a/b; //change
*d = a*b; //change
printf("%lf %lf",*c,*d);
return;
//printf statements
}

int main()
{
//first and second double hold the scanf inputs
double first;
double second;

//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;

printf("Enter your first number\n");
scanf("%lf", &first); //change
printf("Enter your second number\n");
scanf("%lf", &second); //change

//call the function, first and second by value, &c / &d by reference - correct?
myFunction(first, second, &c,&d);
}

C - Passing Structure Parameters to Function By Reference and Value

First of all, variables you have tried to pass (either by value or by reference) when you are calling the two functions capture() and display(), haven't used anywhere because you are dealing directly with the members of the structure Students when you are capturing or displaying the results.

And the reasons you are getting syntax errors are because the capture() is expecting the addresses of the variables (&name,&age,&address,&course) and you are passing variables (name,age,address,course) themselves. And also you are using,

scanf ("%s", &aStudent[i].name);

instead of

scanf ("%s", aStudent[i].name);

In my opinion instead of making the Structure array global, declaring it inside main function and passing the whole structure array to the capture() as a reference and passing it by value to the display() is better to your objective as you need to use both call by value and reference in your code.

I have edited your code a bit and added the return to main menu option. It works for me and I apologize if my answer is long and hard to understand because this is my first answer in stackoverflow. Thanks!

#include <stdio.h>

struct Students
{
int ID;
char name[50];
int age;
char address[100];
char course[30];
};

void capture(struct Students *aStudent)
{
int i;

for(i=0; i<2; i++)
{
aStudent[i].ID = i+1;

printf("\nFor Student number %d:\n",aStudent[i].ID);

printf("Enter Student Name: ");
scanf ("%s", aStudent[i].name);

printf("Enter Student Age: ");
scanf ("%d", &aStudent[i].age);

printf("Enter Student Address: ");
scanf ("%s", aStudent[i].address);

printf("Enter Course: ");
scanf ("%s", aStudent[i].course);
}
}

void display(struct Students aStudent[])
{
int i;

for(i=0; i<2; i++)
{
printf("\nStudent %d:\n",aStudent[i].ID);
printf("Name: %s\t\tAge: %d\t\tAddress: %s\t\tCourse: %s",aStudent[i].name, aStudent[i].age, aStudent[i].address,aStudent[i].course);

printf("\n");
}
}

void main()
{
struct Students aStudent[2];
int option;
char choice = 'Y';

printf("\t...Welcome to the Student Data System...\n\n");

while(choice == 'Y' || choice == 'y')
{
printf("\nPlease Select An Option: \n1. Input Student Data\n2. View Student Data\n3. Exit Syatem\n\n");
scanf("%d",&option);
switch(option)
{
case 1:
printf("Enter Student Details:\n");
capture(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 2:
printf("\nDisplaying Information:\n");
display(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 3:
close();
break;
default:
printf("\nSorry, your option is not valid.");
}

}

}

I ask for clarification about ''not pass by reference'' in C

Or is the function asking for a pointer and when we use & it creates a pointer to that variable?

That's exactly right.

In C++, the symbol & has multiple meanings:

  • When applied as a unary operator in an expression, it means "take the address of", and produces a pointer;
  • When part of a type like int& (or, indeed, int*&), it means "reference to";
  • (And, when applied as a binary operator between two arithmetic expressions, it means "bitwise AND".)

With the choice of using & for reference types, the idea was, I think, to save creating new symbols and to try to create some symmetry between pointers and references. I don't think it worked; I think it's really confusing.

But for you, in C, it's moot, because (as you've discovered!) C does not have references. Instead your function could be written to take a pointer-to-pointer (int**). Ironically, you will probably need to use & at the call-site to present your argument to such a function!

As a further complication, you will sometimes hear the phrase "pass by reference" used in a broad sense. This is confusing in the realm of C++ because "reference" has this more specific meaning there. In fact, references were introduced in the C++ language specifically to make "pass by reference" more elegant and intuitive. But back in C, and more generally, it's just a way of saying "we're referring to a thing rather than copying it"; technically in C the way we do that is, indeed, to pass a pointer.

Meaning of pass by reference in C and C++?

In colloquial usage, "pass by reference" means that, if the callee modifies its arguments, it affects the caller, because the argument as seen by the callee refers to the value as seen by the caller.

The phrase is used independent of the actual programming language, and how it calls things (pointers, references, whatever).

In C++, call-by-reference can be done with references or pointers. In C, call-by-reference can only be achieved by passing a pointer.

"Call by value":

void foo( int x )
{
// x is a *copy* of whatever argument foo() was called with
x = 42;
}

int main()
{
int a = 0;
foo( a );
// at this point, a == 0
}

"Call by reference", C style:

void foo( int * x )
{
// x is still a *copy* of foo()'s argument, but that copy *refers* to
// the value as seen by the caller
*x = 42;
}

int main()
{
int a = 0;
foo( &a );
// at this point, a == 42
}

So, strictly speaking, there is no pass-by-reference in C. You either pass the variable by-value, or you pass a pointer to that variable by-value.

Is passing pointer by value or by reference the same

What is the difference between passing a pointer by reference and passing a pointer by value in C?

There is no such thing as passing a pointer by reference in C, all variables are passed by value, even pointers.

My understanding is when you pass arguments to methods a new stack frame is created and those values are copied to different memory addresses unless passed by reference. If passed by reference the memory addresses are passed.

Again, the pointers are not passed by reference, a copy of the value stored in the pointer is passed, i.e. the address where it points to, you can test this by changing the value of the pointer inside the function, and check how that reflects on the original pointer, spoiler, it doesn't.

When working with pointers I noticed that if I pass a char by value and modify it in a different stack frame when I return back to the main stack frame the value of the ptr has been modified.*

What you are passing is an address, a memory location where some data is stored, when you change the data stored in that memory address it will be permanent, no matter where you do it, in fact that is one of the advantages of using pointers, for you to change the contents of some variable outside the scope where it's declared.



Related Topics



Leave a reply



Submit