my method before is when the function prototype's parameter have * , then it is pass by address~ ~
& : reference
NOTHING : VALUE
This is right
To your previous posts:
so pass address not means the function prototype's parameter must be * in front of parameter.. , right?
When you want the argument to be passed by address you need the * before the parameter: void f ( int *p );
can i haven't initialized p1 as
int *p1;
and use this
*p1 = &firstvalue; // p1 = 0xefefefef
If you declared p1 int *p1; you should use this: p1 = &firstvalue;
will it change the argument value when using passing by address , after cpu finish the called function?
All the changes you do on *pointer will affect the value of the argument
Here is an example:
1 2 3 4 5
void function ( int *pointer )
{
*pointer = 123; // modifies the argument
pointer++; // doesn't modify the argument, it moves 'pointer' to the next position of memory
}
You are getting it but not 100% ( this is the most difficult C++ thing to figure out )
when a * in front of a variable/ parameter/ argument--> then it means that it use it address of it~ ~
This is true on declarations, on a variable is the &
1 2 3
int *pointer; // * = will have a memory address as value
int x;
pointer = &x; // & = return memory address of x
& is the reference operator and can be read as "address of"
* is the dereference operator and can be read as "value pointed by"
Right
1 2 3
int tom =7;
int ted= 14;
ted= &tom ; //ted and tom also = 7 now
not really, for that you should use just ted = tom;
This code souldn't work, &tom is a pointer to int. If you cast it: ted = int ( &tom ); ted will have as value the memory address of tom.
A different thing is this:
1 2 3
int tom = 7;
int &ted = tom; // declare ted as reference and initialize it to be the same as tom (pretty unuseful)
// Notice: now &ted == &tom
func happy(int &h); and func happy(int *h) are two different overloads
To clarify:
1 2 3 4 5 6 7
// This stuff with the function parameter h
func happy(int *h) { .... }
happy ( &first_value );
// Is very similar to this with variable yint *y;
y = &first_value;
use & in the parameter when u want the change show in call function~ ~
Right
use & in the argument when u don't want the change show in call function~ ~
Not right:
Using pointers, you can still modify the value. This was the way it was done in C, without references.
If you don't want to modify the argument, you can pass by value:
void func(int h) { h= 12 ;}
main// error: should be int main()
{
int H = 7;
func (int &H );// error: no int and to use &H func should be declared void func ( int *h )
cout << H ;
}
This is the correct syntax for that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//of course here goes #include etc.
void func(int *h) // notice the *
{
*h = 12; // notice the *
}
int main ()
{
int H = 7;
func ( &H );
cout << H ; // h will be 12
return 0;
}