📝

C++ Functions Lecture Notes

Jun 26, 2024

C++ Functions Lecture Notes

Introduction

  • Welcome to the first video on C++ functions.
  • Important for beginners: check out the playlist on C++ for beginners for foundational concepts.
  • Functions are crucial for understanding and using C++ effectively and are key concepts in most programming languages.

Subscribe and Follow

  • Subscribe to the channel and click the bell icon for notifications on new videos.
  • Follow on Instagram and Twitter (@CodeBeauty) for behind-the-scenes content.

What is a Function?

  • Definition: A function is a block of code grouped together to solve a specific problem or perform a specific task.
  • Executed only when called (invoked).
  • Every C++ program has at least one function, main.

main Function

  • Role: The first function executed in a C++ program.
  • The program starts at the first line of main and ends at the last line or a return statement.
  • Example: int main() { std::cout << "Hello from main" << std::endl; return 0; }
  • Output: "Hello from main"

Creating Your Own Functions

  • Steps to Create a Function:
    1. Return Type: Use void for functions that do not return a value.
    2. Function Name: Choose a descriptive name.
    3. Parameters: Enclose in parentheses; can be empty if no parameters.
    4. Function Body: Enclose in curly brackets {}.
  • Example: void sayHello() { std::cout << "Hello from function" << std::endl; }

Invoking Functions

  • Functions must be called to execute their code.
  • Example invocation within main: int main() { std::cout << "Hello from main" << std::endl; sayHello(); return 0; }
  • Output: Hello from main Hello from function

Function Definition and Declaration

  • Definition: The actual body of the function.
  • Declaration: The header of the function providing return type, name, and parameters.
  • Declarations should be placed before main and definitions after main for readability.
  • Example: void sayHello(); // Declaration int main() { sayHello(); return 0; } void sayHello() { // Definition std::cout << "Hello from function" << std::endl; }

Importance of Functions

  • Readability: Make code easier to read and manage by grouping tasks together.
  • Reusability: Write code once, use it multiple times by invoking the function wherever needed.
  • Maintainability: Easier for others to read, understand, and maintain the code.
  • Example demonstrating reusability: int main() { sayHello(); sayHello(); sayHello(); return 0; }

Conclusion

  • Functions make your code modular, readable, reusable, and maintainable.
  • More details on functions will be covered in future videos.
  • Subscribe and follow on social media for updates and additional content.

Subscription and Social Media

  • Don't forget to subscribe and click the bell icon for notifications.
  • Follow on Instagram and Twitter (@CodeBeauty) for extra content and updates.

Thank you for watching! See you in the next video.