C++ Syntax

C++ syntax refers to the rules and structure used to write C++ code. These rules define how we should organize and structure our code, including how we declare variables, create functions, and write control flow statements.

Example:


#include <iostream>  // Preprocessor directive to include the standard input-output library

using namespace std;  // Declares the standard namespace

// Main function - execution starts here
int main() {
    // Statements
    cout << "Hello, Friends!" << endl;  // Output a message to the console
    return 0;  // Exit status of the program
}

Explanation:

include: A preprocessor directive that includes header files (such as iostream for input/output).

using namespace std;: This line tells the compiler to use the std (standard) namespace, which contains standard library features like cout.

main(): The main function is where the program starts executing.

return 0;: Returns 0 to indicate successful execution.

Note: In C++, each statement ends with a semicolon (;).

C++ Syntax – Questions and Answers

Q 1: Is C++ case-sensitive?

Ans: Yes, C++ is case-sensitive.

Q 2: What are curly braces {} used for?

Ans: To define blocks of code.

Q 3: Are semicolons mandatory?

Ans: Yes, each statement must end with a semicolon.

Q 4: Can whitespace affect program execution?

Ans: No, except within strings.

Q 5: What is a statement in C++?

Ans: A complete instruction that performs an action.

C++ Syntax – Objective Questions (MCQs)

Q1. Which of the following is the correct syntax to output “Hello World” in C++?






Q2. Which header file is required for using cout and cin in C++?






Q3. What is the correct syntax of the main function in C++?






Q4. Which of the following is used to take input from the user in C++?






Q5. Which of the following lines correctly ends a C++ statement?






Related C++ Syntax Topics