mirror of
https://github.com/kamranahmedse/developer-roadmap.git
synced 2025-08-24 18:03:06 +02:00
Add information about function pointer (#4460)
This commit is contained in:
@@ -19,6 +19,20 @@ int *ptr = # // Pointer 'ptr' now points to the memory address of 'num'
|
||||
int value = *ptr; // Value now contains the value of the variable that 'ptr' points to (i.e., 10)
|
||||
```
|
||||
|
||||
**Function pointer:**
|
||||
|
||||
```cpp
|
||||
int add(int a, int b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main()
|
||||
{ int (*funcptr) (int, int) = add; // Pointer 'funcptr' now points to the functions 'add'
|
||||
funcptr(4, 5); // Return 9
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
A reference is an alias for an existing variable, meaning it's a different name for the same memory location. Unlike pointers, references cannot be null, and they must be initialized when they are declared. Once a reference is initialized, it cannot be changed to refer to another variable.
|
||||
@@ -38,4 +52,4 @@ int &ref = num; // Reference 'ref' is now an alias of 'num'
|
||||
|
||||
Modifying the value of `ref` will also modify the value of `num` because they share the same memory location.
|
||||
|
||||
**Note:** References are generally used when you want to pass a variable by reference in function arguments or when you want to create an alias for a variable without the need for pointer syntax.
|
||||
**Note:** References are generally used when you want to pass a variable by reference in function arguments or when you want to create an alias for a variable without the need for pointer syntax.
|
||||
|
Reference in New Issue
Block a user