Basic_syntax
Basic Syntax and Program Structure
Section titled “Basic Syntax and Program Structure”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.
The Structure of a C++ Program
Section titled “The Structure of a C++ Program”Every C++ program follows a specific structure. Understanding this structure is crucial for writing valid C++ code.
Minimal C++ Program
Section titled “Minimal C++ Program”// This is a comment - it helps explain the code// Comments are ignored by the compiler
// Include necessary headers#include <iostream>
// Main function - program entry pointint main() { // Your code goes here return 0;}Breakdown of the Structure
Section titled “Breakdown of the Structure”┌─────────────────────────────────────────┐│ #include <iostream> │ ← Preprocessor directives├─────────────────────────────────────────┤│ int main() { │ ← Function definition│ return 0; │ ← Function body (statement)│ } │└─────────────────────────────────────────┘Preprocessor Directives
Section titled “Preprocessor Directives”The preprocessor runs before compilation and processes directives that start with #.
Include Directive
Section titled “Include Directive”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>Macro Definitions
Section titled “Macro Definitions”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;#endifNote: In modern C++, prefer const and constexpr over macros.
Include Guards
Section titled “Include Guards”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 onceThe main() Function
Section titled “The main() Function”Every C++ program must have a main() function as its entry point.
Function Signature Variations
Section titled “Function Signature Variations”// Standard (most common)int main() { return 0;}
// With command-line argumentsint main(int argc, char* argv[]) { // argc = argument count // argv = argument values return 0;}
// C++17 alternativeint main(int argc, char* argv[]) { return 0;}Return Values
Section titled “Return Values”int main() { // 0 or EXIT_SUCCESS = successful completion // EXIT_FAILURE = error occurred return 0;}Statements and Expressions
Section titled “Statements and Expressions”Statements
Section titled “Statements”A statement is a complete instruction that performs an action:
int x; // Declaration statementx = 5; // Assignment statementstd::cout << x; // Output statement; // Empty statement (does nothing)Expression Statements
Section titled “Expression Statements”An expression is a combination of values, variables, and operators that produces a result:
int x = 5 + 3; // Expression: 5 + 3, result: 8int y = x * 2; // Expression: x * 2, result: 16Compound Statements (Blocks)
Section titled “Compound Statements (Blocks)”A block is a group of statements enclosed in braces:
{ int x = 10; std::cout << x; // More statements}Comments
Section titled “Comments”Comments are ignored by the compiler but help humans understand the code.
Single-Line Comments
Section titled “Single-Line Comments”// This is a single-line commentint x = 5; // Inline commentMulti-Line Comments
Section titled “Multi-Line Comments”/* This is a multi-line comment */Documentation Comments
Section titled “Documentation Comments”/// This is a documentation comment (for tools like Doxygen)/// \param x The input value/// \return The resultint function(int x) { return x * 2; }Identifiers and Naming Rules
Section titled “Identifiers and Naming Rules”Identifiers are names given to variables, functions, classes, etc.
- Can contain letters, digits, and underscores
- Must start with a letter or underscore
- Cannot be a C++ keyword
- Case-sensitive (
myVar≠myvar) - Cannot contain special characters or spaces
Valid and Invalid Names
Section titled “Valid and Invalid Names”int myVariable; // Validint _private; // Valid (but avoid starting with _)int MY_CONSTANT; // Validint count2; // Valid
// Invalid:// int 2count; // Can't start with digit// int my-var; // Can't use hyphen// int class; // Can't use keywordNaming Conventions
Section titled “Naming Conventions”| Convention | Example | Use Case |
|---|---|---|
| camelCase | myVariable | Variables, functions |
| PascalCase | MyClass | Classes, types |
| snake_case | my_variable | Python-influenced code |
| SCREAMING_SNAKE | MAX_SIZE | Constants |
Whitespace and Formatting
Section titled “Whitespace and Formatting”C++ generally ignores extra whitespace, but good formatting makes code readable.
Whitespace
Section titled “Whitespace”// These are equivalent:int x=5;int x = 5;int x = 5 ;Line Breaks
Section titled “Line Breaks”// All statements can be on one lineint x = 5; int y = 10; std::cout << x + y;
// But this is more readable:int x = 5;int y = 10;std::cout << x + y;Indentation
Section titled “Indentation”Use consistent indentation (typically 4 spaces or a tab):
// Good indentationif (condition) { doSomething(); doSomethingElse();}
// Bad indentationif (condition) {doSomething(); doSomethingElse();}Scope determines where a name is visible.
Block Scope
Section titled “Block Scope”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;}Global Scope
Section titled “Global Scope”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
Section titled “Namespaces”Namespaces organize code and prevent name conflicts.
Using Namespaces
Section titled “Using Namespaces”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 std Namespace
Section titled “The std Namespace”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.
Input and Output
Section titled “Input and Output”Standard Output (cout)
Section titled “Standard Output (cout)”#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;}Standard Input (cin)
Section titled “Standard Input (cin)”#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;}Reading Multiple Values
Section titled “Reading Multiple Values”int a, b, c;std::cin >> a >> b >> c; // Enter: 10 20 30Putting It All Together
Section titled “Putting It All Together”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 functionint add(int a, int b) { return a + b;}
// Main function - program entry pointint 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: JohnEnter two numbers: 5 7Hello, John!5 + 7 = 12Common Errors to Avoid
Section titled “Common Errors to Avoid”1. Missing Semicolons
Section titled “1. Missing Semicolons”// Errorint x = 5
// Correctint x = 5;2. Unmatched Braces
Section titled “2. Unmatched Braces”// Errorif (condition) { doSomething();// Missing }
// Correctif (condition) { doSomething();}3. Case Sensitivity
Section titled “3. Case Sensitivity”int MyVariable = 10;int myvariable = 20; // These are DIFFERENT variables!
std::Cout << MyVariable; // Error! Should be std::cout4. Undefined Variables
Section titled “4. Undefined Variables”int main() { int x; std::cout << x; // Error: x is not initialized return 0;}Key Takeaways
Section titled “Key Takeaways”- Every C++ program needs a
main()function as its entry point - Preprocessor directives (starting with
#) are processed before compilation - Use include guards or
#pragma onceto 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
cinfor input andcoutfor output
Next Steps
Section titled “Next Steps”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