harveytech
harveytech

Reputation: 207

Distinction between passing i and &i to a function

What is the difference between the following pairs of statments?

   int i;
   doSomethingWith(i);

and

   int i;
   doSomethingWith(&i);

Upvotes: 1

Views: 98

Answers (3)

Pieter
Pieter

Reputation: 1831

  • Passing 'i' --> pass the value of i (value inside the memory location)
  • Passing '&i' --> pass a reference to the memory location of 'i'

Upvotes: 0

Qaz
Qaz

Reputation: 61970

In C, the & is the address-of operator. So instead of passing a copy of i like you do in the first call, you pass the address of i, or &i, which means the function can modify it directly.

The function will look like this:

void doSomethingWith (int *var);

This means it takes a pointer (something that holds the address) to an integer (in this case, i). Then, to modify i directly, the function can do:

*var = 5;

This is the dereferencing operator, which gives you what is actually stored at that address. This call will assign 5 to what is stored at the memory location you pass with &i.

Any C textbook should explain this in great detail when it talks about pointers.

Upvotes: 4

fbernardo
fbernardo

Reputation: 10124

In the first you're passing the value of i. In the second you're passing the address, in memory, of the variable i.

Have a look at this video about pointers and that kind of stuff.

Upvotes: 2

Related Questions