Basic Syntax of C++

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn what a C++ program is like, and some basic syntaxes and the execution process of a C++ program.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") subgraph Lab Skills cpp/comments -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/variables -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/data_types -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/operators -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/conditions -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/while_loop -.-> lab-178534{{"`Basic Syntax of C++`"}} cpp/function_parameters -.-> lab-178534{{"`Basic Syntax of C++`"}} end

C++ Standards

C++ is standardized as ISO/IEC 14882. Currently, there are two versions:

  1. C++98 (ISO/IEC 14882:1998): 1st standard version of C++.
  2. C++03 (ISO/IEC 14882:2003): minor "bug-fix" to C++98 with no change to the language. Commonly refer to as C++98/C++03 or First C++ standard.
  3. C++11 (ISO/IEC 14882:2011): 2nd standard version of C++. Formerly called C++0x, as it was expected to finalize in 200x. It adds some new features to the language; more significantly, it greatly extends the C++ standard library and standard template library (STL).

C++ Features

  1. C++ is C. C++ supports (almost) all the features of C. Like C, C++ allows programmers to manage the memory directly, so as to develop efficient programs.
  2. C++ is OO. C++ enhances the procedural-oriented C language with the object-oriented extension. The OO extension facilitates design, reuse and maintenance for complex software.
  3. Template C++. C++ introduces generic programming, via the so-called template. You can apply the same algorithm to different data types.
  4. STL. C++ provides a huge set of reusable standard libraries, in particular, the Standard Template Library.

C++ Strength and Pitfall

C++ is a powerful language for high-performance applications, including writing operating systems and their subsystems, games and animation. C++ is also a complex and difficult programming language, which is really not meant for dummies. To effectively use the C++ Standard Template Library (STL), you need to understand these difficult concepts: pointers, references, operator overloading and template, on top of the object-oriented programming concepts such as classes and objects, inheritance and polymorphism; and the traditional constructs such as decision and loop. C++ is performance centric. The C++ compiler does not issue warning/error message for many obvious programming mistakes, undefined and unspecified behaviors, such as array index out of range, using an uninitialized variable, etc, due to the focus on performance and efficiency rather than the ease of use - it assumes that those who choose to program in C++ are not dummies.

Revision

Below is a simple C++ program that illustrates the important programming constructs (sequential flow, while-loop, and if-else) and input/output. Write the code below in test.cpp file and save it. For examples,

/*
 * Sum the odd and even numbers, respectively, from 1 to a given upperbound.
 * Also compute the absolute difference.
 */
#include <iostream>   // Needed to use IO functions
using namespace std;

int main() {
   int sumOdd  = 0; // For accumulating odd numbers, init to 0
   int sumEven = 0; // For accumulating even numbers, init to 0
   int upperbound;  // Sum from 1 to this upperbound
   int absDiff;     // The absolute difference between the two sums

   // Prompt user for an upperbound
   cout << "Enter the upperbound: ";
   cin >> upperbound;

   // Use a while-loop to repeatedly add 1, 2, 3,..., to the upperbound
   int number = 1;
   while (number <= upperbound) {
      if (number % 2 == 0) {  // Even number
         sumEven += number;   // Add number into sumEven
      } else {                // Odd number
         sumOdd += number;    // Add number into sumOdd
      }
      ++number; // increment number by 1
   }

   // Compute the absolute difference between the two sums
   if (sumOdd > sumEven) {
      absDiff = sumOdd - sumEven;
   } else {
      absDiff = sumEven - sumOdd;
   }

   // Print the results
   cout << "The sum of odd numbers is " << sumOdd << endl;
   cout << "The sum of even numbers is " << sumEven << endl;
   cout << "The absolute difference is " << absDiff << endl;

   return 0;
}

Output:

Enter the upperbound: 1000
The sum of odd numbers is 250000
The sum of even numbers is 250500
The absolute difference is 500

open the terminal here, and use g++ -o test test.cpp to compile the source file, it will generate an executable file under the same folder with the source file.

image desc

Program Notes

using namespace std;
The names cout and endl belong to the std namespace. They can be referenced via fully qualified name std::cout and std::endl, or simply as cout and endl with a "using namespace std;" statement. For simplicity, I shall use the latter approach in this section. I will discuss the significance later.

return 0;
The return value of 0 indicates normal termination; while non-zero (typically 1) indicates abnormal termination. C++ compiler will automatically insert a "return 0;" at the end of the the main() function, thus, it statement can be omitted.

Instead of using numeric value of zero and non-zero, you can also use EXIT_SUCCESS or EXIT_FAILURE, which is defined in the cstdlib header (i.e., you need to "#include <cstdlib>".

Comments

Comments are used to document and explain your codes and program logic. Comments are not programming statements and are ignored by the compiler, but they VERY IMPORTANT for providing documentation and explanation for others to understand your program (and also for yourself three days later).

There are two kinds of comments in C/C++:

  1. Multi-line Comment: begins with a /* and ends with a */, and can span several lines.
  2. End-of-line Comment: begins with // and lasts till the end of the current line.

You should use comments liberally to explain and document your codes. During program development, instead of deleting a chunk of statements permanently, you could comment-out these statements so that you could get them back later, if needed.

Statements and Blocks

Statement: A programming statement is the smallest independent unit in a program, just like a sentence in the English language. It performs a piece of programming action. A programming statement must be terminated by a semi-colon (;), just like an English sentence ends with a period. (Why not ends with a period like an english sentence? This is because period crashes with decimal point - it is hard for the dumb computer to differentiate between period and decimal point!)

For examples

// Each of the following lines is a programming statement, which ends with a semi-colon (;)
int number1 = 10;
int number2, number3 = 99;
int product;
product = number1 * number2 * number3;
cout << "Hello" << endl;

Block: A block (or a compound statement) is a group of statements surrounded by braces { }. All the statements inside the block is treated as one unit. Blocks are used as the body in constructs like function, if-else and loop, which may contain multiple statements but are treated as one unit. There is no need to put a semi-colon after the closing brace to end a complex statement. Empty block (without any statement) is permitted. For examples,

// Each of the followings is a "complex" statement comprising one or more blocks of statements.
// No terminating semi-colon needed after the closing brace to end the "complex" statement.
// Take note that a "complex" statement is usually written over a few lines for readability.
if (mark >= 50) {
   cout << "PASS" << endl;
   cout << "Well Done!" << endl;
   cout << "Keep it Up!" << endl;
}

if (number == 88) {
   cout << "Got it" << endl;
} else {
   cout << "Try Again" << endl;
}

i = 1;
while (i < 8) {
   cout << i << endl;
   ++i;
}

int main() {
   //...statements...
}

White Spaces and Formatting Source Codes

White Spaces: Blank, tab and new-line are collectively called white spaces. C++, like most of the computing languages, ignores extra white spaces. That is, multiple contiguous white spaces are treated as a single white space. You need to use a white space to separate two keywords or tokens, e.g.,

int sum=0;          // Need a white space between int and sum
double average;     // Need a white space between double and average
average=sum/100.0;

Additional white spaces and extra lines are, however, ignored, e.g.,

// same as above
int  sum
   =  0 ;

   double  average  ;
average = sum / 100.0;

Formatting Source Codes: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation (with tabs and blanks) and extra empty lines greatly improves the readability of the program, which is extremely important for others (and yourself three days later) to understand your programs.

Braces: Place the beginning brace at the end of the line, and align the ending brace with the start of the statement.

Indentation: Indent the body of a block by an extra 3 (or 4 spaces), according to its level.

For example

/*
 * Recommended Programming style.
 */
#include <iostream>
using namespace std;
                           // blank line to separate sections of codes
int main() {  // Place the beginning brace at the end of the current line
   // Indent the body by an extra 3 or 4 spaces for each level

   int mark = 70;
   if (mark >= 50) {               // in level-1 block, indent once
      cout << "You Pass!" << endl; // in level-2 block, indent twice
   } else {
      cout << "You Fail!" << endl;
   }

   return 0;
}   // ending brace aligned with the start of the statement

Note: Traditional C-style formatting places the beginning and ending braces on the same column. For example,

/*
 * Traditional C-style.
 */
#include <iostream>
using namespace std;

int main()
{
   if (mark >= 50)                 // in level-1 block, indent once
   {
      cout << "You Pass!" << endl; // in level-2 block, indent twice
   }
   else
   {
      cout << "You Fail!" << endl;
   }
}

Preprocessor Directives

C++ source code is pre-processed before it is compiled into object code (as illustrated).

image desc

A preprocessor directive, which begins with a # sign (such as #include, #define), tells the preprocessor to perform a certain action (such as including a header file, or performing text replacement), before compiling the source code into object code. Preprocessor directives are not programming statements, and therefore should NOT be terminated with a semi-colon. For example,

#include <iostream>  // To include the IO library header
#include <cmath>     // To include the Math library header
#define PI 3.14159265    // To substitute the term PI with 3.14159265 in this file
   // DO NOT terminate preprocessor directive with a semi-colon

In almost all of the C++ programs, we use #include <iostream> to include the input/output stream library header into our program, so as to use the IO library function to carry out input/output operations (such as cin and cout).

Summary

In this part, you learned what a C++ program is like, and some basic syntaxes and the execution process of a C++ program.

Other C++ Tutorials you may like