Chapter 2: Basic Syntax & First Program

Basic Syntax & First Program: Your First Steps in C++ – Let’s Build It Together!

Hey there, future C++ pro! Welcome to the second lesson. If you’re coming from the intro, great job getting your environment set up (Visual Studio, VS Code + compiler, or online like Godbolt). Today we’re going to write, understand, and run your very first real C++ program—the classic “Hello World”—and then break down every single line and concept like I’m sitting next to you, pointing at the screen.

Think of this as learning to drive a car: First, we learn the controls (syntax), then we take a short, safe drive (Hello World), and finally we understand why the dashboard looks the way it does. We’ll go super detailed, with examples, common mistakes, and tips to avoid frustration.

By the end, you’ll be able to:

  • Write and run a basic C++ program
  • Understand the structure of every C++ file
  • Use comments properly
  • Format code so it’s readable (super important!)

Ready? Open your editor/IDE and create a new file called hello.cpp. Let’s go!

Step 1: The Famous “Hello World” Program – Your First Victory

Here’s the complete program we’ll build together. Type it in exactly (or copy-paste if you’re in a rush), then we’ll dissect it.

C++

Now, compile and run it:

  • Visual Studio: Press Ctrl + F5 (or the green “Start Without Debugging” button). You should see a console window pop up with:
    text
  • VS Code + GCC/Clang: In terminal: g++ hello.cpp -o hello then ./hello (Linux/Mac) or hello.exe (Windows).
  • Online (Godbolt or OnlineGDB): Paste, select C++23 or latest, hit Run.

Success? High-five! 🎉 That little program just ran on your computer. Now let’s understand why it works.

Step 2: Program Structure – The Anatomy of a C++ File

Every C++ program follows a similar structure. Think of it as a house: foundation, walls, roof.

  1. Comments (optional, but super helpful)
  2. #include directives (bring in libraries)
  3. using namespace (optional shortcut)
  4. The main() function – the heart of the program!

Let’s break down each part from our example:

  • Comments:
    • // Single-line comment → Everything after // on that line is ignored by the compiler.
    • /* Multi-line comment */ → Can span multiple lines. Great for license info or big explanations.
    • Tip from teacher: Use comments to explain why you wrote code a certain way, not just what it does. Bad: // add 1 Good: // add 1 to account for zero-based indexing.
  • #include <iostream>:
    • This is a preprocessor directive (starts with #). It tells the compiler: “Before compiling, copy the contents of the file iostream here.”
    • <iostream> is part of the C++ Standard Library. It gives us tools like cout (console output) and cin (console input).
    • Common mistake: Forgetting the #include. You’ll get errors like “cout was not declared in this scope”.
    • Angle brackets < > → for standard library headers.
    • Double quotes ” ” → for your own header files (we’ll cover later).
  • using namespace std;:
    • std is a namespace – like a family name for all standard library stuff (std::cout, std::endl, std::string, etc.).
    • Writing using namespace std; says: “In this file, when I write cout, I mean std::cout.” It saves typing.
    • Pro tip: In big projects, avoid using namespace std; at the top (it can cause name conflicts). Instead, write std::cout or use using std::cout; for specific items.
    • Example without it:
      C++
  • int main() { … }:
    • This is the entry point – the first function the program runs.
    • int means it returns an integer (number) to the operating system.
    • () means no parameters (arguments) for now.
    • { } curly braces define the block of code that belongs to main().
    • Everything inside { } runs in order, line by line.
    • return 0; → Convention: 0 means “success”. Any other number means “error” (you can return 1 for failure).
  • The Output Line:
    C++
    • cout = console output (pronounced “see-out”)
    • << = insertion operator (like putting things into a stream)
    • “Hello…” = a string literal (text in double quotes)
    • endl = end line (adds newline + flushes output)
    • You can chain multiple << on one line – very convenient!

Try modifying it! Change the message, add more lines, remove endl and see what happens (no new line!).

Step 3: Code Formatting & Style – Make It Beautiful!

C++ doesn’t care about spaces, tabs, or new lines (except inside strings). But you should care – good formatting = readable code = fewer bugs.

Bad (works but ugly):

C++

Good (professional style):

C++

Rules I teach my students:

  • Indent everything inside { } by 4 spaces or 1 tab (consistency!).
  • Put { on the same line as the function name (Allman style is also fine).
  • One statement per line.
  • Space around operators: a + b not a+b.
  • Empty line between logical sections.
  • Use meaningful variable names (later lessons).

Tools to help:

  • VS Code: Install “C/C++” extension → Auto-format on save (Ctrl+Shift+I).
  • Visual Studio: Ctrl+K, Ctrl+D to format.
  • Online: Most have auto-indent.

Step 4: Common Beginner Mistakes & How to Fix Them

Mistake Error Message Fix
Forgot semicolon ; expected ‘;’ before ‘}’ Add ; after every statement
Mismatched { } expected ‘}’ at end of input Count your braces
Forgot #include <iostream> ‘cout’ was not declared Add the include
Typed Cout instead of cout identifier not found C++ is case-sensitive!
No return 0; (usually warning) Always add it in main()

Bonus: A Slightly Fancier First Program

Let’s add input so you see interactivity!

C++

Run it → Type your name → See personalized greeting!

Homework & Next Steps

  1. Run the Hello World program 5 times, changing the message each time.
  2. Remove using namespace std; and fix it by adding std:: everywhere.
  3. Add comments explaining each line.
  4. Try the name-input version.

Next lesson: Variables, data types, and basic input/output. You’re doing great – the first program is always the hardest!

Questions? Confused about anything? Paste your code and error here – I’ll help debug like a real teacher. You’ve got this! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *