C++ Pointers and Functions šŸŽÆ

beginner
14 min

C++ Pointers and Functions šŸŽÆ

Welcome to our deep dive into C++ Pointers and Functions! This lesson is designed for both beginners and intermediate learners, so let's get started! šŸ“

Understanding Pointers šŸ’”

Pointers in C++ are variables that store the memory address of another variable.

cpp
int num = 10; int* pNum = # // Here, pNum is a pointer that stores the memory address of num

Why use Pointers?

  1. Dynamic Memory Allocation: Pointers allow you to dynamically allocate and deallocate memory during runtime.
  2. Function Parameters and Return Values: Pointers are used to pass and return data to and from functions.
  3. Pointers to Functions: Allows the manipulation of functions as data.

Pointer Operations šŸ’”

  1. Accessing the Value Stored in a Pointer: *pNum
  2. Assigning a Value to a Pointer: pNum = &otherVariable
  3. Checking if a Pointer is Null: if(pNum == nullptr)
  4. Incrementing or Decrementing a Pointer: pNum++ or pNum--

C++ Functions šŸ’”

Functions in C++ are blocks of reusable code, which perform specific tasks.

cpp
void greet() { cout << "Hello, World!"; }

Function Types šŸ’”

  1. void: A function that doesn't return any value.
  2. int: A function that returns an integer value.
  3. char: A function that returns a character value.
  4. double: A function that returns a floating-point value.

Passing Arguments to Functions šŸ’”

  1. Pass by Value: The function creates a copy of the argument.
  2. Pass by Reference: The function uses a reference (&) to the argument.
  3. Pass by Pointer: The function uses a pointer (*) to the argument.

Functions with Pointers šŸ’”

  1. Passing a Function as an Argument: void myFunction(void (*ptrFunc)())
  2. Returning a Pointer from a Function: int* myFunction()
  3. Pointers to Arrays: int* pArr = new int[10];

Practical Example šŸ’”

cpp
#include <iostream> void printValue(int value) { std::cout << "Value: " << value << std::endl; } int main() { int num = 10; int* pNum = &num; printValue(*pNum); int arr[] = {1, 2, 3, 4, 5}; int* pArr = arr; for(int i = 0; i < 5; i++) { std::cout << *pArr++ << std::endl; } return 0; }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the purpose of a pointer in C++?

Quick Quiz
Question 1 of 1

What is the purpose of the `&` operator in C++?