C++: Complete Developers Guide Part -1

Syed Khizaruddin
12 min readJan 23, 2022

--

C++, the mother of all programming language

C++ Fast development reference khizaruddins, khizaruddins.medium.com mother of programming language
Photo by Alex Pasarelu on Unsplash

Introduction:

C++ was developed by Danish computer Scientist Bjarne Stroustrup at Bell Labs in 1979 as an extension of the C language.

C is the basic programming language and, intro to computer programming world, for me, so if you are complete beginner, Pls read it carefully, If someone is willing to learn programming language, this is the first good step towards your goal.

This blog is curated in such a way that any programming language can be learned, just the syntax varies and some programming language specific built-in functions or libraries.

Some terminologies for understanding:

  1. Compiler: A compiler takes a program and converts it into machine executed code; it takes the whole program file and compiles it.
  2. Interpreter: An interpreter takes a program and interprets it into machine code; it takes one line as an input and interprets it, one line or statement at a time.
  3. Assembler: An assembler takes the assembly language and converts it into machine code.
  4. Linker: It is a computer program that links and merges various object files together in order to create an executable file.
  5. Loader: It is a part of the operating system and is responsible for loading executable files into memory and executing them; calculating the size of a program (instructions and data) and creating memory space for it, are some of its features.
C++ fast development reference, see plus plus, c++ khizaruddins, khizaruddins.medium.com
Photo by David Travis on Unsplash

Moving on,

C++ is more of a compiled language; it is compiled first, then it is executed.

Note: The word compile means converting a program into byte code or machine code so that a machine can execute it.

Hence, we have a C++ compiler to compile c++ programs; any machine having a c++ compiler can run C++ programs; that’s why it is called platform independent.

There are basically Static, Dynamic, Strongly and Weakly Typed programming languages

c++ fast development reference static type khizaruddins khizaruddins.medium.com
Photo by Amos from Stockphotos.com on Unsplash

1. Static typed:

Statically typed languages are those which do type checking at compile time. Without type definition, these programs give compile time errors.

That means it is important to add a type of value which a variable will hold.

C++ is a static typed language.

NOTE: Variables and types are covered in later sections.

C++ fast development reference khizaruddins khizaruddins.medium.com dynamic type
Photo by Fraser Cottrell on Unsplash

2.Dynamic typed:

Dynamic typed languages are those which do type checking at run time.

That means even if type is not added, at run-time, the according to the value it holds, the program itself understands which type of data is given.

Javascript is a dynamic typed language.

C++ fast development reference, khizaruddins, khizaruddins.medium.com strong typed
Photo by Clay Banks on Unsplash

3. Strongly Typed:

In strongly typed languages two unrelated types of data cannot be converted implicitly, i.e. two different types of data cannot be merged into a single type of data.

int a, res;
string b;
res = a + b; // <- this will give compile time error

This will give an error while compilation is done.

C++ is a strongly typed language.

C++ fast development reference khizaruddins, khizaruddins.medium.com weak type
Photo by Erika Fletcher on Unsplash

4. Weakly typed (loosely type):

In weakly typed languages, two unrelated types of data can be converted implicitly. i.e., two different types of data can be merged into a single type of data. For eg. Javascript.

let a = 0;
let b = "Hello";
let res = a + b; // no error

This won’t give an error; instead the value of res will become ‘Hello0’ with type as string.

C++ fast development reference khizaruddins khizaruddins.medium.com, setting c++ up
Photo by Adi Goldstein on Unsplash

SETUP Environment C++:

  1. Windows: To set up c++ on windows. Pls go through this link.
  2. Mac OS: To set up c++ on mac, pls go through this link.
  3. Linux Ubuntu: To set up c++ on ubuntu, pls go through this link.

Let’s start with our first Hello World C++ program:

#include <iostream>int main() {  std::cout << "Hello world" << std::endl;  return 0;}

Note: ‘::’ is called scope resolution operator. We will talk later in the upcoming parts

To compile this code on vs code press ‘ctrl + option + N’.

If you get stuck in a running loop press ‘ctrl + option + M’, to break execution.

In terminal, execute the compiled program by ‘./filename’

Output: Hello world

In the above code we can see ‘#include’ is used for importing some necessary header file. After using this line we can use ‘cin’, ‘cout’ functions inside our main function.

The ‘cin’ function is used to take input from the user from the terminal.

The ‘Cout’ function is used to output or print some log or information for a user.

The ‘endl’ is used to give a line break.

The ‘std’ is used to point to the ‘cin’ and ‘cout’ functions.

We can get rid of this ‘::’ using namespace as below.

#include <iostream>using namespace std;int main() {  cout << "Hello world" << endl;  return 0;}

The ‘main’ function is the only function which gets executed when the program is loaded; it is the entry point of our program. The ‘main’ function is prefixed with an int-keyword which tells that the ‘main’ function should return an integer value.

Note — Keywords are those words whose meaning is already defined by Compiler. These keywords cannot be used as an identifier. Note that keywords are a collection of reserved words and predefined identifiers.

Note- Identifiers — The C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9)

There are 90 keywords, to get list of all available keywords pls visit: here

Photo by David Pupaza on Unsplash

Types of Errors in code:

1. Compile time errors:

Errors which occur at the time of compilation, when we violate the rule of writing syntax then this error is thrown. This type of error is highlighted by the compiler line number and is easy to find.

eg. Forgetting a semicolon.

#include <iostream>using namespace std;int main(){  int x = 10;  int y = 15;  // semicolon missed  cout << " "<< (x, y);}

Error:

Error: expected ';' before '}' token

2. Runtime errors:

Errors which occur at the runtime, the most common runtime error is a divide by zero error. This type of error is not highlighted by the compiler and is hard to find.

#include <iostream>using namespace std;int main(){int n = 9, div = 0;   // wrong logic   // number is divided by 0,   // so this program abnormally terminates   div = n/0;   cout <<"result = " << div;}

Error:

Warning: division by zero [-Wdiv-by-zero]
div = n/0;

3. Logical Errors:

The desired output is not obtained after compilation and running code is logical errors. Logical errors are errors due to the wrong logical implementation; for this we need to debug our code to find out the root cause.

For eg. printing numbers from 1 to 10 code below

#include <iostream>using namespace std;int main() {  for (int i = 1; i < 10; i++){    cout << i;  }  return 0;}

Output:

1 2 3 4 5 6 7 8 9

Here, as i = 1, it is comparing till i < 10; so, when i becomes 9 this for loop will run and print 9 but when i becomes 10; and as 10<10 is false, the loop will stop; the correct logical condition should be i≤10.

4. Linker errors:

These errors occur when after compilation we link the different object files with the main object. These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, and/or incorrect header files. One of the most common linker errors is writing Main() instead of main().

5. Resource errors:

Resource errors are those when we try to open a file in a program and that file does not exist or some header file which we try to import and those header file does not exist.

Variables and its Types:

Programs are user interaction which takes user input, performs some calculation, or executes according to logic given and gives an output.

The input given by the user is stored in a variable, so in a program it can be used.

c++ fast development reference khizaruddins, khizaruddins.medium.com container variable and types
Photo by TAN Erica on Unsplash

A variable can be thought of as an empty container where we can put some value.

User input values can be numbers, strings, float values, negative numbers etc. These input needs to be stored in memory so that we can use it in a program. According to the type of value, we can store data in different memory sizes.

Hence, based on the data we store, we allocate memory size by defining the type of data the variable will hold.

Data types are divided into three types:

1. Primitive data types:

These data types are built-in or predefined data types and can be used directly by the user to declare variables. Example: int, char, float, bool etc

2. Derived data types:

These data types are derived from primitive or built-in data types which are four only functions, array, pointer, and reference.

3. Abstract or user defined data type:

These data types are defined by the user itself. Like, defining a class in C++ or a structure. Class, Structure, Union, Enumeration, Typedef defined datatype are some example.

Note- We will cover derived and abstract in later sections.

Variable Declaration and Assignment, Initialization:

#include <iostream>int main() { int a;}

A variable is declared simply by giving its type as given below

int age;

Here int is a keyword used to denote variable name age will hold integer value.

string name;

Here string is a keyword used to denote variable name ‘name’ that will hold string as a value.

Similarly char is for single character float is for decimal numbers bool holds boolean value i.e. true and false value etc.

Initialization of variable:

The very first time a value is set on a variable, then it is called variable initialization.

For eg.

int count; // variable declarationcount = 0; // variable initialization

We can do both in one line

int count = 0;

Naming a variable must not be very random it must be related to what the value holds.

If there is a complex name there are some cases which we follow while naming variables as follows:

  1. Camel case: first letter of word remains small and first letter of second word will be capital joining both words without spaces. For eg. firstName, lastName.
  2. Snake case: Spaces between words will be replaced with underscores (_) and all letters will be lower case letters. For eg first_name, last_name.
  3. Kebab case: Spaces between words will be replaced with hyphens (-) and all letters will be lower case letters. For eg first-name, last-name. Mostly this case is not used in programming language instead it is used in Frontend CSS for class name and ids in xml and in lisp language as well.
  4. Pascal case: All letters of all words will be capitalized and it will be joined with no spaces. For eg FirstName, LastName.
  5. Upper snake case: All letters of all words will be upper case letters two or more words are separated by an underscore(_) for eg. FIRST_NAME, LAST_NAME. Usually these are used to store some constants like for eg api key. For eg. API_KEY, FIREBASE_KEY.

It is up to us, to use any case, but I recommend using Camel case or snake case.

Kebab cases are not supported by c++ or any programming language except some like LISP.

Constants:

Constants are variables which are declared with values that cannot be altered or changed at a later point of time, if the const value are changed after initialization it will throw a compile time error.

#include <iostream>int main () {   const int abc; // constant declaration   const float PI = 3.14; // constant declaration with
// initialisation
}

Control flow:

It is important to know what control flow is in a programming language.

Control flow is the flow at which a program is executed, the flow at which instructions, statements, loops, and functions are executed.

For example in below program,

#include <iostream>using namespace std;int main() {  int c, a, b;  cout << "Enter two numbers" << endl;  cin >> a >> b;  c = a + b;  cout << "the sum of two number is " << c << endl;  return 0;}

NOTE: ‘>>’ is called stream insertion operator and ‘<<’ is called string extraction operator.

Control executes one line at a time from top to bottom.

In above program, control scans first line and includes necessary files important to use cout, cin, endl etc. Then it scans next line and understands std (short form of ‘standard’) as namespace whose members are used in program which are cout, cin, endl, The control then scans main function

Here, main function is the entry point of the program meaning whatever it is written inside main function will get executed, that doesn’t means #include is not required and namespace too, those lines makes other functions, available to be used inside main function (like cin, cout, endl etc.)

Each line inside the main function is read by the control and is executed.

When control hits the return and 0 is returned to operating system, that means program terminated successfully, and if its not 0 then operating system checks what went wrong.

First c, a, b variables are declared with data type as ‘int’, then “Enter two number “ message is printed then two inputs are taken from user, unless two inputs are entered the control flow is paused when user presses enter key, the user entered values are stored in variable a and b as per the order of number entered, then the value of a and b is added and stored in c, and finally the sum of two values are printed.

Comments:

Comments are programmer readable explanations in the code, such an explanation conveys what the program does, comments are never compiled and it get striped out, before the compiler starts seeing the program.

Through comments one developer can convey what exactly is happening in the code so that other developers can read those comments and get an understanding of what the program is doing.

There is single line and multiline comment in any programming language.

#include <iostream>using namespace std;int main () {   int a; // single line comment this is not read by compiler    /*
This is a multiline comment
I.e. everything inside this is for developers to read
Which is not seen by compiler
*/ return 0;}

Comments should be used wisely, we should not comment which are obvious and are understandable, comments are very useful, when your code is complex in such cases commenting is better so that other programmers can understand what is happening.

The position of comment also matters, hence for statement its best to put above that statement, in functions, we need to place comments just above function declaration, will see functions in later sections.

When we change a function or statement which already has a comment, we need to update the comment as well for later use.

For eg. if i’m looking at the below code

#include <iostream>int main() {   int c, a, b;

// addition of a and b
c = a + b; cout << "the sum is:\n" << c; return 0;
}

So if I change this code to subtraction as below,

#include <iostream>int main() {int c, a, b;

// addition of a and b <- needs to update comment to subtraction
c = a - b; cout << "the sum is:\n" << c; return 0;
}

We need to update the comment as well so that other developers understands what it is doing, in this case it is a very small program but what if we write some complex calculations that time it comes handy.

The second part of this series can be found by clicking here.

Pls, do share this with as many people as you can.

Thanks.

TLDR;

For more tech related blogs please visit:

khizaruddins.medium.com
Follow me on twitter and instagram
Buy me a coffee.

--

--