Skip to content

Basic_syntax

Now that you have your development environment set up, it’s time to learn the fundamental syntax of C++. This chapter covers the building blocks of every C++ program, from the basic structure to statements, blocks, and how code is organized.

Every C++ program follows a specific structure. Understanding this structure is crucial for writing valid C++ code.

// This is a comment - it helps explain the code
// Comments are ignored by the compiler
// Include necessary headers
#include <iostream>
// Main function - program entry point
int main() {
// Your code goes here
return 0;
}
┌─────────────────────────────────────────┐
│ #include <iostream> │ ← Preprocessor directives
├─────────────────────────────────────────┤
│ int main() { │ ← Function definition
│ return 0; │ ← Function body (statement)
│ } │
└─────────────────────────────────────────┘

The preprocessor runs before compilation and processes directives that start with #.

The #include directive inserts the contents of another file:

// Standard library header
#include <iostream>
// User-defined header (in current directory)
#include "myheader.h"
// Multiple includes
#include <iostream>
#include <string>
#include <vector>

Macros create symbolic constants or code templates:

// Define a constant
#define PI 3.14159
// Define a code template
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// Conditional compilation
#ifdef DEBUG
std::cout << "Debug mode" << std::endl;
#endif

Note: In modern C++, prefer const and constexpr over macros.

Prevent multiple inclusions of header files:

// Method 1: Traditional include guards
#ifndef MY_HEADER_H
#define MY_HEADER_H
// Header contents here
#endif
// Method 2: C++17 #pragma once (simpler, but not standard)
#pragma once

Every C++ program must have a main() function as its entry point.

// Standard (most common)
int main() {
return 0;
}
// With command-line arguments
int main(int argc, char* argv[]) {
// argc = argument count
// argv = argument values
return 0;
}
// C++17 alternative
int main(int argc, char* argv[]) {
return 0;
}
int main() {
// 0 or EXIT_SUCCESS = successful completion
// EXIT_FAILURE = error occurred
return 0;
}

A statement is a complete instruction that performs an action:

int x; // Declaration statement
x = 5; // Assignment statement
std::cout << x; // Output statement
; // Empty statement (does nothing)

An expression is a combination of values, variables, and operators that produces a result:

int x = 5 + 3; // Expression: 5 + 3, result: 8
int y = x * 2; // Expression: x * 2, result: 16

A block is a group of statements enclosed in braces:

{
int x = 10;
std::cout << x;
// More statements
}

Comments are ignored by the compiler but help humans understand the code.

// This is a single-line comment
int x = 5; // Inline comment
/* This is a
multi-line
comment */
/// This is a documentation comment (for tools like Doxygen)
/// \param x The input value
/// \return The result
int function(int x) { return x * 2; }

Identifiers are names given to variables, functions, classes, etc.

  1. Can contain letters, digits, and underscores
  2. Must start with a letter or underscore
  3. Cannot be a C++ keyword
  4. Case-sensitive (myVarmyvar)
  5. Cannot contain special characters or spaces
int myVariable; // Valid
int _private; // Valid (but avoid starting with _)
int MY_CONSTANT; // Valid
int count2; // Valid
// Invalid:
// int 2count; // Can't start with digit
// int my-var; // Can't use hyphen
// int class; // Can't use keyword
ConventionExampleUse Case
camelCasemyVariableVariables, functions
PascalCaseMyClassClasses, types
snake_casemy_variablePython-influenced code
SCREAMING_SNAKEMAX_SIZEConstants

C++ generally ignores extra whitespace, but good formatting makes code readable.

// These are equivalent:
int x=5;
int x = 5;
int x = 5 ;
// All statements can be on one line
int x = 5; int y = 10; std::cout << x + y;
// But this is more readable:
int x = 5;
int y = 10;
std::cout << x + y;

Use consistent indentation (typically 4 spaces or a tab):

// Good indentation
if (condition) {
doSomething();
doSomethingElse();
}
// Bad indentation
if (condition) {
doSomething();
doSomethingElse();
}

Scope determines where a name is visible.

int main() {
int x = 10; // x is visible here
if (true) {
int y = 20; // y is only visible in this block
std::cout << x; // x is still visible
}
// std::cout << y; // ERROR: y is not visible here
std::cout << x; // x is still visible
return 0;
}
int globalVar = 100; // Global variable
void function() {
globalVar = 200; // Can access global variable
}
int main() {
std::cout << globalVar; // 100
function();
std::cout << globalVar; // 200
return 0;
}

Namespaces organize code and prevent name conflicts.

namespace MyNamespace {
int myVar = 10;
}
// Access with ::
int x = MyNamespace::myVar;
// Using directive (be careful - brings all names into scope)
using namespace std;
cout << "Hello"; // Without std::

The standard library uses the std namespace:

#include <iostream>
int main() {
// Without using directive
std::cout << "Hello" << std::endl;
// With using directive
using namespace std;
cout << "Hello" << endl;
// Using specific names
using std::cout;
using std::endl;
cout << "Hello" << endl;
return 0;
}

Best Practice: Avoid using namespace std; in header files and large projects. Use std:: prefix or using for specific names.

#include <iostream>
int main() {
int age = 25;
std::cout << "Hello, World!" << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Age: " << age << "\n";
// Multiple values
std::cout << "Value: " << 42 << " and " << 3.14 << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << name << "!" << std::endl;
std::cout << "You are " << age << " years old." << std::endl;
return 0;
}
int a, b, c;
std::cin >> a >> b >> c; // Enter: 10 20 30

Here’s a complete example demonstrating the concepts covered:

// A simple C++ program demonstrating basic syntax
#include <iostream>
#include <string>
// Using directive for std (OK in small programs)
using namespace std;
// Simple function
int add(int a, int b) {
return a + b;
}
// Main function - program entry point
int main() {
// Declaration and initialization
string name;
int num1, num2, sum;
// Input
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter two numbers: ";
cin >> num1 >> num2;
// Processing
sum = add(num1, num2);
// Output
cout << "Hello, " << name << "!" << endl;
cout << num1 << " + " << num2 << " = " << sum << endl;
// Return success
return 0;
}

Sample Output:

Enter your name: John
Enter two numbers: 5 7
Hello, John!
5 + 7 = 12
// Error
int x = 5
// Correct
int x = 5;
// Error
if (condition) {
doSomething();
// Missing }
// Correct
if (condition) {
doSomething();
}
int MyVariable = 10;
int myvariable = 20; // These are DIFFERENT variables!
std::Cout << MyVariable; // Error! Should be std::cout
int main() {
int x;
std::cout << x; // Error: x is not initialized
return 0;
}
  • Every C++ program needs a main() function as its entry point
  • Preprocessor directives (starting with #) are processed before compilation
  • Use include guards or #pragma once to prevent multiple inclusions
  • Statements end with semicolons (;)
  • Blocks are groups of statements enclosed in curly braces ({ })
  • Use comments to explain your code
  • Follow consistent naming conventions
  • Use the std:: prefix or namespaces to avoid name conflicts
  • Use cin for input and cout for output

Now that you understand basic syntax, let’s dive into variables and data types in the next chapter.

Next Chapter: 04_variables_datatypes.md - Variables and Data Types