C++ Basic Concepts
It is important that you understand the basic concepts of C++ before you start writing a program in C++.
Basic C++ Syntax
Syntax is a rule and regulation for writing a statement in any programming language. It is like a grammatical rule which defines the structure of a program. Every programming language has their own unique syntax, C++ also has its own syntax.
We can learn the C++ basic Syntax with the following program:
#include <iostream>
using namespace std;
int main()
{
int num1 = 24;
int num2 = 34;
int result = num1 + num2;
cout << result << endl;
return result;
}
The above program shows the basic C++ program that contains header files, namespace declaration, main function, etc.
Header File
The header file contains the definitions of predefined functions that can be imported or included using the preprocessor directive #include. It is declared at the top of a C++ program. In our above example code, we are importing an iostream header file that provides basic input output streams for the programs. The iostream header file is a part of the C++ standard library that uses the cin and cout method for input and the output.
Syntax
#include <iostream>
Namespace
In C++, a namespace is a part of a code that provides a scope to the identifiers like functions, the name of types, classes, variables, etc. Namespaces are used to organize code logically and avoid name conflicts, which are especially likely to happen when your code base contains several libraries.
Syntax
namespace namespace_name {
//Declarations
}
Main Function
Functions are the block of code used to perform a specific task. The main function is an important part of a program in C++. It is the entry point of a C++ program. The main() function is the first thing that is called when a C++ program is run. The main() method can be found in every C++ program.
Syntax
void main() {
// code here
}
In the above syntax, void is a keyword which means nothing in C++. When a function is declared with the void keyword, then the function should not return anything. Here, main is the name of the function that is predefined in the C++ standard library.
Variables
A variable is a container name given to a location in computer memory to store and retrieve data. Every variable must have a unique name to identify the storage location.
Syntax
type variableName = value;
In C++, a variable declaration should always start with a declaration of datatype, followed by variable name. Example: int number = 1;
Blocks and Semicolons
Blocks are groups of statements that are written within {} braces. Semicolons are used to terminate statements . When there is a semicolon in the statement, the compiler knows it is the end of the statement and moves to the next line.
Syntax
{
any_statement ;
}
Keywords
Keywords are reserved words that have special meaning to the compilers. In C++ there are 95 keywords. For example, int, using, return, void are some keywords used in the above program.