C++ Syntax



This article explains the C++ Syntax.

Properly the Syntax of the language before you begin will save you from alot of confusion and syntax errors in the future. The Syntax that we explain below is code that you’re going to be repeating in almost every single C++ program that you make.


Code Sample

We’ll be using the code sample below across the article.

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!";
  return 0;
}

From the above code, we’ll be discussing the following Syntax related topics.

  • Libraries and Namespace
  • Curly Brackets
  • Main Function
  • Semi-Colons

Libraries and Namespace

#include <iostream>
using namespace std;

The #include <iostream> line is a Header File Library that brings in several functions and commands related to input and output objects.

The using namespace std is related to variable naming, namespace and to some degree classes as well. It’s OK if you don’t understand this right now, but we’ll try to explain it through the following example.

This is what the following line looks like with the namespace line.

cout << "Hello World!";

Without the namespace import, this is what it looks like.

std:: cout << "Hello World";

Curly Brackets

Some language like Python rely on Indentation to define code blocks. Other languages like Java and C++ rely on the use of Curly brackets to “enclose” a block of code. You will typically see these in functions and loops.

Below is a short demonstration of a simple function.

int add(int x, int y){
    return x + y;
}

Anything within the two curly brackets is part of the function. Curly brackets also create their own local namespace. Any variable declared between the curly brackets will only be accessible within the curly brackets.


Semi-colons

int main() {
  cout << "Hello World!";
  return 0;
}

C++ requires that you add a Semi Colon at the end of every statement. This is to declare that the line has finished. In the code sample above, there are only two statements, hence both have a semi-colon at the end.

As you begin coding, you’ll gain a sense of where to add a semi-colon and where not to. Just remember, never add a semi-colon at the end of a bracket.


Main() function

The Main function in your code is always the most important. It’s quite literally the “main” function which always executes when your program is run. You can think of it as the entry point for the program, from where the code begins executing.

In case you didn’t already understand, it’s necessary for each (C++) program to have a main function. If you read the examples above again, you’ll notice this.


This marks the end of the C++ Syntax article. Any suggestions or contributions for CodersLegacy are mire than welcome. Questions regarding the article content can be asked in the comments section below.

Leave a Reply

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