System Programming Topic

C++ Basic Syntax

Tokens in C++

Tokens are the smallest individual elements of a C++ program. They are:

  1. Keywords (Reserved words)

  2. Identifiers (Variable/function names)

  3. Literals (Constant values)

  4. Operators (+, -, *, /, =, etc.)

  5. Punctuators (; , {} () [] etc.)

  6. Separators (Whitespace)

Example:

cpp

#include <iostream>  // Tokens: #include, <iostream>
                     // < and > are punctuators

int main() {         // Tokens: int, main, (, ), { 
    int x = 10;      // Tokens: int, x, =, 10, ;
    return 0;        // Tokens: return, 0, ;
}     
               // Token: }

Keywords (Reserved Words)

C++ has 95 keywords (as of C++20). They cannot be used as identifiers.

Common Keywords by Category:

Data Types:

cpp

bool, char, int, float, double, void
auto, short, long, signed, unsigned

Modifiers:

cpp

const, volatile, mutable, static, extern

Control Flow:

cpp

if, else, switch, case, default
for, while, do, break, continue
goto

Functions:

cpp

return, inline, virtual, explicit

Classes & Objects:

cpp

class, struct, union, enum
public, private, protected
this, friend, operator, template
new, delete, sizeof, typeid, typename

OOP Concepts:

cpp

virtual, override, final

Exception Handling:

cpp

try, catch, throw

Storage Classes:

cpp

auto, register, static, extern, thread_local

C++11+ Modern Keywords:

cpp

// C++11
nullptr, decltype, constexpr, noexcept
alignas, alignof, static_assert
thread_local

// C++14
constexpr (enhanced)

// C++17
if constexpr, inline (for variables)

// C++20
concept, requires, co_await, co_yield, co_return
char8_t, consteval, constinit

Type Casting:

cpp

dynamic_cast, static_cast, const_cast, reinterpret_cast

Complete Alphabetical List:

text

alignas        alignof        and           and_eq
asm            auto           bitand        bitor
bool           break          case          catch
char           char8_t        char16_t      char32_t
class          compl          concept       const
consteval      constexpr      const_cast    continue
co_await       co_return      co_yield      decltype
default        delete         do            double
dynamic_cast   else           enum          explicit
export         extern         false         float
for            friend         goto          if
inline         int            long          mutable
namespace      new            noexcept      not
not_eq         nullptr        operator      or
or_eq          private        protected     public
register       reinterpret_cast requires    return
short          signed         sizeof        static
static_assert  static_cast    struct        switch
template       this           thread_local  throw
true           try            typedef       typeid
typename       union          unsigned      using
virtual        void           volatile      wchar_t
while          xor            xor_eq

Identifiers

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

Rules for Identifiers:

  1. First character: Must be a letter (a-z, A-Z) or underscore (_)

  2. Subsequent characters: Can be letters, digits (0-9), or underscores

  3. Case-sensitive: myVar and myvar are different

  4. Cannot be a keyword

  5. No special characters: @, $, %, etc. are not allowed

  6. No whitespace

  7. Length: No practical limit (but compiler dependent)

Valid Identifiers:

cpp

int myVariable;
float _privateData;
char student_name;
double PI_VALUE;
string fileName2;
auto calculateTotal();
class EmployeeRecord;

Invalid Identifiers:

cpp

int 2ndValue;     // Starts with digit
float my-var;     // Contains hyphen
char switch;      // Keyword
double my var;    // Contains space
string @email;    // Special character

Naming Conventions:

cpp

// Camel Case (common for variables/functions)
int studentCount;
void calculateTotalAmount();
string fileName;

// Pascal Case (common for classes)
class EmployeeRecord;
struct NodeData;
enum ColorType;

// Snake Case (common in C/C++)
int student_count;
void calculate_total_amount();
string file_name;

// UPPER_CASE (constants)
const double PI = 3.14159;
#define MAX_SIZE 100

// Hungarian Notation (old style, not recommended)
int iCount;      // i for integer
char szName[50]; // sz for zero-terminated string
float fPrice;    // f for float

Comments

Comments are used for documentation and to disable code temporarily.

1. Single-line Comments:

cpp

// This is a single-line comment
int x = 10;  // Variable declaration with comment at end

// Multiple single-line comments
// Each line needs //

2. Multi-line Comments:

cpp

/* 
   This is a multi-line comment
   It can span multiple lines
   Useful for longer explanations
*/

int y = 20;  /* Inline comment */

/*
   Nested comments are NOT allowed in C++
   /* This would cause error */
*/

3. Modern Documentation Comments:

cpp

/**
 * @brief Calculates the sum of two numbers
 * @param a First number
 * @param b Second number
 * @return Sum of a and b
 */
int add(int a, int b) {
    return a + b;
}

/// Single-line documentation comment
/// @param radius Circle radius
/// @return Area of circle
double circleArea(double radius);

Comment Best Practices:

cpp

// GOOD: Explain WHY, not WHAT
// Calculate factorial for probability calculation
int factorial(int n) {
    // Base case: factorial of 0 is 1
    if (n == 0) return 1;
    
    // Recursive calculation
    return n * factorial(n - 1);
}

// BAD: Obvious comments
int x = 5;  // Set x to 5 (obvious!)

// GOOD: Comment complex algorithms
// Using Floyd's cycle detection algorithm
bool hasCycle(Node* head) {
    // Implementation...
}

// Use comments to temporarily disable code (debugging)
/*
void debugFunction() {
    cout << "Debug info" << endl;
}
*/

main() Function

The main() function is the entry point of every C++ program. It's where execution begins.

Basic Structure:

cpp

int main() {
    // Program code here
    return 0;  // Indicates successful execution
}

Valid main() Signatures:

cpp

// Most common
int main() {
    return 0;
}

// With command-line arguments
int main(int argc, char* argv[]) {
    // argc: Argument count
    // argv: Argument vector (array of strings)
    return 0;
}

// Alternative for argv
int main(int argc, char** argv) {
    return 0;
}

// With environment variables (non-standard but widely supported)
int main(int argc, char* argv[], char* envp[]) {
    return 0;
}

Detailed Explanation:

1. Return Type:

  • Must be int (returns exit status to operating system)

  • return 0; indicates success

  • Non-zero indicates error (convention: 1 for general error)

2. Command-line Arguments:

cpp

#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << "Number of arguments: " << argc << std::endl;
    
    // argv[0] is always the program name
    std::cout << "Program name: " << argv[0] << std::endl;
    
    // Process other arguments
    for(int i = 1; i < argc; i++) {
        std::cout << "Argument " << i << ": " << argv[i] << std::endl;
    }
    
    return 0;
}

Compile and run:

bash

g++ program.cpp -o program
./program arg1 arg2 "arg 3"

Output:

text

Number of arguments: 4
Program name: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg 3

3. Implicit return:

C++ allows omitting return 0; in main() (only in main!)

cpp

int main() {
    std::cout << "Hello World!" << std::endl;
    // No return statement - implicitly returns 0
}

Complete Example Program:

cpp

#include <iostream>   // Header for input/output
#include <string>     // Header for string type

// Function declaration
void greetUser(const std::string& name);

// Global constant (UPPER_CASE naming)
const int MAX_ATTEMPTS = 3;

// main() function - program entry point
int main(int argc, char* argv[]) {
    /* 
       Program: Simple Greeting Application
       Author: John Doe
       Date: 2024
    */
    
    // Display program info
    std::cout << "=== Greeting Program ===" << std::endl;
    
    // Check command-line arguments
    if(argc > 1) {
        // If name provided as argument
        greetUser(argv[1]);
    } else {
        // Ask for name
        std::string userName;
        std::cout << "Enter your name: ";
        std::cin >> userName;
        
        // Call function
        greetUser(userName);
    }
    
    // Demonstrate variables
    int attemptCount = 0;     // camelCase for variables
    const float PI = 3.14159f; // UPPER_CASE for constants
    
    // Return success
    return 0;
}

// Function definition
void greetUser(const std::string& name) {
    // PascalCase for function name
    std::cout << "Hello, " << name << "!" << std::endl;
    std::cout << "Welcome to C++ programming!" << std::endl;
}

Common Variations and Notes:

Alternative main() with auto:

cpp

// C++14: auto return type deduction (not recommended for main)
auto main() -> int {
    return 0;
}

Void main() - NOT Standard:

cpp

// This is NOT standard C++!
// Some compilers allow it, but avoid for portability
void main() {
    // No return needed
}

Environment Variables:

cpp

// Non-standard but widely supported
int main(int argc, char* argv[], char* envp[]) {
    // Print environment variables
    for(int i = 0; envp[i] != nullptr; i++) {
        std::cout << envp[i] << std::endl;
    }
    return 0;
}

Error Handling in main():

cpp

#include <iostream>
#include <cstdlib>  // for EXIT_SUCCESS, EXIT_FAILURE

int main() {
    try {
        // Program logic here
        std::cout << "Program running..." << std::endl;
        
        // Simulate error condition
        bool errorOccurred = false;
        
        if(errorOccurred) {
            return EXIT_FAILURE;  // Return 1
        }
        
        return EXIT_SUCCESS;  // Return 0
    }
    catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch(...) {
        std::cerr << "Unknown error occurred" << std::endl;
        return EXIT_FAILURE;
    }
}

Compilation Process:

cpp

// Step 1: Create source file (example.cpp)
#include <iostream>

int main() {
    std::cout << "Hello C++!" << std::endl;
    return 0;
}

// Step 2: Compile
// g++ example.cpp -o example

// Step 3: Run
// ./example

Common Errors and Solutions:

1. Missing Semicolon:

cpp

// ERROR
int x = 10  // Missing semicolon
std::cout << x

// CORRECT
int x = 10;
std::cout << x;

2. Using Keywords as Identifiers:

cpp

// ERROR
int class = 5;      // 'class' is a keyword
float new = 3.14;   // 'new' is a keyword

// CORRECT
int myClass = 5;
float newValue = 3.14;

3. Invalid main() signature:

cpp

// ERROR
void main() {           // Should return int
    // code
}

float main() {          // Must return int
    return 0.0;
}

// CORRECT
int main() {
    return 0;
}

Best Practices:

  1. Use meaningful identifiers: studentCount not sc

  2. Follow consistent naming conventions

  3. Comment complex logic, not obvious code

  4. Always include return statement in main() for clarity

  5. Handle command-line arguments when needed

  6. Use constants for magic numbers

  7. Keep main() focused - delegate logic to functions

Quick Reference Card:

cpp

// Basic C++ Program Template
#include <iostream>  // Preprocessor directive
using namespace std; // Optional: avoid std:: prefix

// Global declarations
const int GLOBAL_CONST = 100;

// Function prototypes
void myFunction();

// Class declaration
class MyClass {
    // class members
};

// Main function
int main() {
    // Local variables
    int localVar = 10;
    
    // Function call
    myFunction();
    
    // Output
    cout << "Value: " << localVar << endl;
    
    // Return success
    return 0;
}

// Function definition
void myFunction() {
    cout << "Function called!" << endl;
}

This covers the fundamental building blocks of C++ syntax. Explore these basics before moving to more advanced topics!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?