C++ Syntax
C++ syntax refers to the set of rules that define how a C++ program is written and interpreted by the compiler. Understanding syntax is important because even a small mistake can cause a program to fail during compilation.
Basic Example
Below is a simple C++ program demonstrating basic syntax:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Explanation of the Syntax
- #include <iostream> – Includes the input-output stream library.
- using namespace std; – Allows us to use standard library features without writing std::.
- int main() – The main function where the program starts executing.
- cout << – Used to display output on the screen.
- return 0; – Ends the program and returns a value to the operating system.
Statements
A statement is a single instruction in a C++ program. Each statement must end with a semicolon (;).
int x = 10; cout << x;
Code Blocks
Code blocks are groups of statements enclosed within curly braces { }.
{
int x = 10;
cout << x;
}
Case Sensitivity
C++ is a case-sensitive language. This means that uppercase and lowercase letters are treated differently.
int value = 10; int Value = 20;
In this example, value and Value are two different variables.
Comments
Comments are used to explain the code and make it easier to understand. Comments are ignored by the compiler.
Single-line comment:
// This is a single-line comment
Multi-line comment:
/* This is a multi-line comment */
Next Topic
Next, learn about C++ Variables.