C++ Using Declaration

beginner
25 min

C++ Using Declaration

Welcome to the exciting world of C++ programming! In this lesson, we'll dive into one of the fundamental concepts: Using Declaration. By the end of this lesson, you'll be able to understand and implement the declaration of variables and functions in C++.

Variable Declaration šŸŽÆ

In C++, variables must be declared before they can be used. A declaration tells the compiler about the existence of a variable, its data type, and its name.

cpp
data_type variable_name;

For example, to declare an integer variable named num, you would write:

cpp
int num;

šŸ“ Note: You can also initialize a variable at the time of declaration by assigning it a value:

cpp
int num = 10;

Function Declaration šŸ’”

Similar to variables, functions must also be declared before they can be called. A function declaration provides the compiler with the function's name, return type, and the number and types of parameters.

cpp
return_type function_name(parameter_1_type parameter_1, parameter_2_type parameter_2, ...);

For example, a function named add that takes two integers and returns an integer:

cpp
int add(int a, int b);

You'll learn more about functions, including their implementation, in a future lesson.

Understanding Declaration vs Definition āœ…

While declaration informs the compiler about a variable or function's existence, the definition provides the actual implementation. A variable's definition includes its memory allocation, while a function's definition includes the code that will be executed when the function is called.

For variables, a declaration and definition can be combined:

cpp
int num = 10;

For functions, the declaration and definition are usually separate:

cpp
// Declaration int add(int a, int b); // Definition int add(int a, int b) { return a + b; }
Quick Quiz
Question 1 of 1

What is the purpose of declaring a variable or function in C++?

That's it for our introduction to C++ using declaration! In the next lesson, we'll dive deeper into C++ functions and learn how to write and call them. Stay tuned! šŸš€