Syntax & Structure
Overview
Every single C++ program, no matter how complex, relies on a strict foundational structure. The operating system needs to know exactly where to begin executing your code. In C++, this entry point is always a function named main().
Before the main() function, you typically see 'Preprocessor Directives' (lines starting with #). These tell the compiler to fetch tools from the C++ Standard Library before trying to build the program. Furthermore, C++ is heavily reliant on semicolons (;); they act as the period at the end of a sentence, telling the compiler that a specific instruction is complete.
Syntax
#include <iostream> // 1. Preprocessor Directive: Fetch the Input/Output library
int main() { // 2. The Entry Point: The OS starts here
// 3. The actual code/instructions go inside the curly braces {}
return 0; // 4. Exit Code: Tells the OS the program finished successfully
}Common Pitfalls
- Forgetting the semicolon (
;) at the end of a statement. This is the most common syntax error in C++. Without it, the compiler gets confused and merges two lines of code together. - Misspelling
main. C++ is strictly case-sensitive. If you writeint Main()orint MAIN(), the Linker will violently crash, complaining about an 'undefined reference to main'.
Interview Questions
main() function return an int instead of void?The int returned by main() is an Exit Status Code sent directly to the Operating System. Returning 0 universally signifies that the program executed without errors. Returning any non-zero value (like 1 or -1) signals to the OS that the program crashed or encountered a fatal error.
Real-World Example
Returning dynamic error codes to the Operating System based on runtime failures.
int main() {
bool databaseConnected = connectToDatabase();
if (!databaseConnected) {
// The OS can intercept this '1' and trigger an alert!
return 1;
}
return 0; // Success!
}Check Your Knowledge
Test your understanding of Syntax & Structure with these quick questions.