You are here:

C++/call by refrence

Advertisement


Question
Hi
i have a question about calling variables in functions

could you plz tell me what's the diffrence between:

'a' has an integer type

power(&a)     and     power(*a)

i know that in power(&a) the address of 'a' will be change but will the value of 'a' change too?
or in power(*a) the value of a will change but will the address of it change too?

i mean the main values and addresses,not the values or addresses that we use in function power

Thanx
Bita

Answer
> the address of 'a' will be change

the address of 'a' will never change. once an object is created, it's address in memory never changes.

> will the value change?

yes, it could change. dereference a pointer (address) and you can access the variable.

> in power(*a) ...

this is a compile-time error.
the dereference operation (unary *) is available only on pointers.

void power( int* pointer )
{
  // assign 8 to the int the address of which is in pointer
  *pointer = 8 ;
}

int main()
{
  int a = 9999 ;
  
  // pass a copy of the address of variable 'a' to the function
  // the function can dereference the pointer to access 'a'
  power( &a ) ;
  // now the value of 'a' will be 8

  // compile time error: unary * operator is not defined for integers
  power( *a ) ; // *** error ***
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.