C++ Basic Syntax
C++ Basic Syntax
Section titled “C++ Basic Syntax”A C++ program is fundamentally a collection of functions and types (like classes and structures). Object-Oriented Programming (OOP) views a program as a collection of interacting objects.
- Object: An instance of a class. It has state (data members/variables) and behavior (member functions/methods). Example: A specific
Carobject might have states likecolor = "red",currentSpeed = 50, and behaviors likeaccelerate(),brake(). - Class: A blueprint or template for creating objects. It defines the properties (data members) and actions (member functions) that all objects of that class will have.
- Method (Member Function): A function associated with a class. Methods define the behavior of objects and operate on their data.
- Data Member (Instance Variable): Variables defined within a class that hold the state of an object. Each object (instance) of the class has its own copy of these variables.
C++ Program Structure:
Section titled “C++ Program Structure:”Let’s examine a simple “Hello, World!” program:
// Include the Input/Output Stream library header#include <iostream>
// main() is where program execution begins.int main() { // Use std::cout to print to the console // std::endl inserts a newline and flushes the stream std::cout << "Hello, World!" << std::endl;
// Return 0 to indicate successful execution return 0;}Let’s break down the parts:
#include <iostream>: This is a preprocessor directive. It tells the compiler to include the contents of the<iostream>header file, which contains declarations for standard input/output operations likestd::cout.int main(): This is the main function. Execution of every C++ program begins here. Theintindicates thatmainreturns an integer value to the operating system (conventionally, 0 means success).{ ... }: Braces define a block of code, also known as a compound statement. The body of themainfunction is enclosed in braces.std::cout << "Hello, World!" << std::endl;: This is a statement.std::coutis the standard output stream object (usually the console). The<<operator is the stream insertion operator, used here to send the string literal"Hello, World!"and the manipulatorstd::endl(end line) tostd::cout.std::Namespace Prefix:coutandendlare part of the standard namespace (std). Usingstd::qualifies their names. It’s generally good practice to use thestd::prefix rather thanusing namespace std;at the global scope to avoid potential name collisions.return 0;: This statement terminates themainfunction and returns the value 0 to the calling process (usually the operating system), indicating successful completion.//: Single-line comments start with//and continue to the end of the line./* ... */: Multi-line comments start with/*and end with*/.
Compile & Execute C++ Program:
Section titled “Compile & Execute C++ Program:”To compile and run your C++ code, you typically need a C++ compiler (like g++, Clang, or MSVC) installed.
- Save the code above in a file named
hello.cpp. - Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the code using your compiler. It’s good practice to specify the C++ standard version (e.g., C++17 or C++20) and an output filename:
g++ hello.cpp -o hello -std=c++17(for g++ or Clang)cl hello.cpp /std:c++17 /EHsc /Fe:hello.exe(for MSVC)- If compilation is successful (no errors), an executable file (
helloorhello.exe) will be created. - Run the executable:
./hello(on Linux/macOS)hello.exeor.\hello.exe(on Windows)- You should see
Hello, World!printed on your console.
For larger projects, managing compilation manually becomes tedious. Build systems like CMake or Meson, along with build tools like Make or Ninja, are commonly used to automate the build process.
Semicolons & Blocks in C++:
Section titled “Semicolons & Blocks in C++:”In C++, the semicolon (;) acts as a statement terminator. Each individual instruction or declaration usually ends with a semicolon.
// Three distinct statements:int x = 10;x = x + 5;std::cout << x << std::endl;A block (or compound statement) is a sequence of zero or more statements enclosed in curly braces {}. Blocks group statements logically, often used as the body of functions, loops, or conditional statements. Blocks also define scope.
{ int y = 20; // y is local to this block std::cout << "Inside block." << std::endl;} // y goes out of scope hereWhitespace (spaces, tabs, newlines) is generally ignored by the compiler, except when it’s needed to separate tokens (like int and main). You can format your code with indentation and spacing to improve readability.
C++ Identifiers:
Section titled “C++ Identifiers:”An identifier is a name used to identify entities like variables, functions, classes, types, namespaces, etc. Rules for identifiers:
- Must begin with a letter (a-z, A-Z) or an underscore (
_). - Can be followed by letters, underscores, or digits (0-9).
- Cannot contain punctuation characters like
@,$,%, or spaces. - Are case-sensitive:
myVariableandmyvariableare different identifiers. - Cannot be the same as a C++ keyword.
- Identifiers containing a double underscore (
__) or starting with an underscore followed by an uppercase letter are reserved for the implementation and should be avoided.
Examples of valid identifiers:
value count temp_sensor _internalData MAX_SIZE MyClass processInputC++ Keywords:
Section titled “C++ Keywords:”Keywords are reserved words with special meaning in the C++ language. You cannot use them as identifiers. Here is a non-exhaustive list of common C++ keywords (including some from modern C++ standards):
| Core Types | Control Flow | Loops | User Types | OOP/Access | Memory/Pointers | Modifiers | Modern C++ | Exceptions/Misc |
|---|---|---|---|---|---|---|---|---|
int | double | char | bool | void | ||||
if | else | switch | case | default | ||||
for | while | do | break | continue | ||||
class | struct | enum | union | namespace | ||||
public | private | protected | virtual | override (C++11) | ||||
new | delete | this | nullptr (C++11) | using | ||||
const | static | extern | inline | volatile | ||||
auto (C++11) | decltype (C++11) | constexpr (C++11) | noexcept (C++11) | template | ||||
try | catch | throw | return | sizeof |
Note: This list is illustrative. Consult C++ documentation for the complete set of keywords for a specific standard version.
Trigraphs (Historical Note):
Section titled “Trigraphs (Historical Note):”Historically, C++ supported trigraph sequences (three-character sequences starting with ?? representing single characters like #, [, ], etc.) for environments lacking certain characters. Trigraphs were confusing and rarely used; they were removed from the C++ standard in C++17. You should not use them in modern C++ code.