Writing Professional Code in C++

Good morning, Good afternoon or Good evening accordingly, at whatever time you visit this blog. So many beginners at this point of time might be confused that what is a professional code :P. Well, to be honest, inside every programmer lies a poet and every line or statement of his code reflects the amount of professionalism he possesses. A professional code is something which is definitely easy at the eye and every single line clearly specifies what the programmer intends to achieve via the piece of code.

Style is more than a matter of aesthetic interest. A professional code shows a consistency from start to end, thus making it easier to debug or extend further. Honestly, throughout my entire life, I have not been able to write, what the programmers call as a “Professional or Beautiful Code”. But trust me, a beautiful code presents your approach, more professional, realistic and clear in front of others and that is for what you get appreciated, be it your team, the successor employee, boss and the whole industry as well.

Why should I write professional code?

Consider a scenario, where you are working in a team developing a game of football. A team consists of 5 sub-teams. Each sub-team is provided with a particular objective to accomplish.

  • Team1 writes the code for shooting the ball and the projectile in which the ball will be travelling after the shot is taken.
  • Team2 writes the code for a goalkeeper who intends to save, shoot and dive.
  • Team3 writes the code for climate effects in the match.
  • Team4 writes the code for the formation of teams.
  • Team 5 writes the code for the behavior of players at every moment of the match.

Now suppose you work in Team1 and you need to write the function for kicking the ball. Your function’s input will be the player who is kicking the ball, the skill level of the player and the type of climate. You write 500 lines of code for kicking the ball and return the position where the ball will land and whether the ball is successfully hit or not. A colleague of yours in Team1 is writing the function for the amount of deflection or swing in the ball and also determining whether the ball is intended to be shot at the goal and returns the graphic position of the ball in the air space and the whether the goal has been achieved or not. Suppose he writes 250 lines of code in his function.

A colleague of yours in Team5 is writing the function for the behavior of player after he scores the goal. The input of the function is dependent on the output of the functions written by you and your colleague in Team1. Now, if he encounters a problem due to a fault in your code, he tries to analyse your code and at this point of time, if your code is self-explanatory or beautiful, he might find out the problem and report it to you accordingly.
Now, in future, suppose if you leave your company, while you were engaged in the project and a new lad is hired in order to deal with your code and extend it further as per the requirements of the project.

If your code is very much noob or unprofessional, he will end up not only scratching but banging his head on the desk. At the end of the day, instead of respect++ for your professionalism and expertise, you will be receiving loads of slangs 😛 . Competitive coding also demands beauty in your code so that your teammates can understand the algorithm in a short span of time by the overview of your code. So, to avoid such situations, I bring to you, certain points which will help you to code in a lovely manner –

  1. Maintain the indentation or what we call as “Indent Style”.
  2. Sensible or Meaningful names of any component or module.
  3. Most important “Comments” and “Documentation”.

Indentation Styles

If your code follows a certain design structure or pattern, a form of symmetrical behavior sets up inside the mind and psychologically everybody loves to see symmetry in any object. So, in order to achieve this, we have got certain styles which you can follow in order to beautify up a certain code. But do no end up mixing these styles in the code which will ultimately lead to make your code more worse than it was. 😛

  1. The Allman Style – The Allman style (proposed by Eric Allman) uses broken brackets. The code written in Allman style is as follows –
    int topcode1(int a)
    {
    	if(a==1)
    	{
    		cout<<”Hello World”:
    		return 20;
    	}
    	else
    	{
    		cout<<”Hi World”;
    		return 10;
    	}
    }
    

    I am a fan of the Allman’s Style because every line is vivid and tend out to be more spacious and free. 😀

  2. The Java Style – The Java style uses attached brackets. The code written in Java style is as follows.
    int topcode2(int a) {
    	if(a == 1) {
    		a = topcode1(5);
    		return 10;
    	} else
    		return 20;
    }
    
  3. The KR Style (Kerninghan-Ritchie) – Kerninghan and Ritchie Style uses linux style brackets. Opening brackets are broken from namespaces, classes, and function definitions. Brackets are attached to everything else including statements within a function, arrays, structs and enums. When you stick to KR style, each function has its opening brace at the next line on the same indentation level as the signature of the function at a line of its own. The blocks inside a function, however have their opening braces at the same line of the statement which drives the entire block.
    int topcode3(int a)
    {
    	if(a == 1) {
    		a = topcode2(5);
    		return 10;
    	} else
    		return 20;
    
    }
    
  4. The Stroustrup Style – The Stroustrup Style( a variant of KR style) breaks brackets from function definitions only. Brackets are attached to everything else including namespaces, classes, and statements within a function, arrays, structs, and enums. This style frequently is used with an indent of 5 spaces. The else statement does not forcefully embrace the statement at which the braces of ‘if’ ends.The code written in Stroustrup Style is as follows:-
    int topcode4(int a)
    {
    	if(a==1) {
    		a = topcode3(5);
    		return 10;
    
    	} else
    		return 20;
    }
    
  5. The Whitesmith Style – Whitesmith style uses broken, indented brackets. Switch blocks and class blocks are indented to prevent a ‘hanging incident’ with following case statements and C++ access specifiers (public, private protected).
    int topcode5(int a)
    	{
    	if(a==1)
    		{
    		a = topcode4(5);
    		return 10;
    		}
    	else
    		return 20;
    	}
    
  6. The Visualization Toolkit Style – The VTK style uses broken , indented styles, except for the opening bracket. Switch blocks are indented to prevent a hanging indent with following case statements.
    int topcode6(int a)
    {
    	if(a==1)
    		{
    		topcode5();
    		return 10;
    		}
    	else
    		return 20;
    }
    
  7. The Horstmann Style – Horstmann style uses “run in the same statement” open braces. Switches are indented to allow a run-in to the opening switch block. This style is frequently used with an indent of 3 spaces. This style includes the advantages provided by Allman by making the margin of the alignment uniform vertically and saving of the line which was the feature of KR style.
    int topcode7(int a)
    {	a = topcode5(1);
    	if(a==1)
    	{	printf(“Hello”);
    		return 10;
    	}
    	else
    	{	printf(“Hi”);
    		return 20;
    	}
    }
    
  8. The Pico Style – The Pico style is quite different from the above mentioned styles because of the fact that in “Pico programming Language” there are no return statements and semicolons have the work of separating the statements instead of terminating them. Opening braces are broken and allow run-in statements. The closing braces are along with the last line in the block. Switches are indented to allow a run-in to the opening switch block. This style frequently is used with an indent of 2 spaces. So in the case the code will have the following structure.
    void topcode8(int a)
    {	a = topcode6(1);
    	a = topcode5(2); }
    
  9. The Ratliff Style – The Ratliff Style also known as the banner style , is analogous to 1TBS style in the way it starts. The style makes it easier to analyse the stuff visually, since the headers of any block are the only thing extended at that level. It uses attached and indented brackets.
    int topcode9(int a) {
    	if(a%2) {
    		a = topcode7(1);
    		return 10;
    		}
    	else {
    		a = topcode8(2);
    		return 20;
    		}
    	}
    	}
    
  10. The 1TBS style – The One true Brace style( a variant of KR style). The main point which distinguishes it from the the other styles is that the one line conditionals also need to be enclosed in braces. An example code to demonstrate the fact is as follows:-
    int topcode10(int a)
    {
    	if(a%2)   {
    		a = topcode8(1);
    	} else   {
    		a = topcode9(2);
    	}
    }
    
  11. The GNU style – The GNU style combines the Allman and WhiteSmith style by putting braces on line by themselves, and indentation of two spaces, except when opening a function definition, where thery are not indented.
    int topcode11(int a)
    {
    	if(a%2)
    		{
    			a = topcode9(1);
    			a = topcode10(2);
    		}
    }
    
    

So, these are some major indentation styles which one can follow in order to write a sincere and beautiful code . The main difference between indent styles listed above lies in the placement of braces of the compound statement that often follows a control statement. There are also some other indentation styles which are not mentioned above like linux kernel form, Berkley software distribution kernel form which are something more specific and used in the source tree of the respective organizations. You can even end up creating your own indentation style, the only criteria being that it does not look horrible and follow a definite pattern or certain points which makes the whole indentation symmetric and easy-to-recognize stuff 😛 .

Remember after every opening brace, when the next line starts, please get it into your reflexes that you enter the tab button of keyboard and not indent it using spaces. Although this war between tabs and spaces goes on, I am one of the soldiers of the “tab” army, because its really a good practice.

Naming Components and Modules

As the subtopic says, the code which you write is segmented into certain modules or functions. It also consists of variables and class or structure blocks. All these things are present in your code in order to serve a specific purpose demanded by the problem statement. The variables or function names should be such that if anyone reads the function signature or variable name , he will spontaneously be able to guess the purpose for which it has been written. Suppose if you allocate a two dimensional array at some point of time and you write a specific function, a name like alloc2D() or 2Dallocation() or mem2D() would work fine instead of writing big words such as allocatetwodimensionalarray() or writing small names such as 2D().

I do not possess any rights to change the views of any professional programmer, but I think this helps a lot, in the long run. The variables should also be named in accordance with the purpose they intend to serve. Some naming conventions represent rules or requirements which are outside the domain of the specific project or problem domain and are defined by a overwhelming set of software architecture. One example is the HUNGARIAN NOTATION. This notation is absolutely language independent and is recognized naming convention for identifiers.

Hungarian Notation is of two types :- Apps Hungarian and System Hungarian.

In this notation, a variable name starts with a group of lower case letters which are mnemonics for the type or purpose of that variable. It also follows the CamelCase where the first character of the given variable name is capitalized to separate it from those which mention the type or the type indicators. Some examples are

pX :- Denotes a pointer to type X

sz:- Denotes a null or zero terminated string

There are many other examples such as positional notation which is mainly active in mainframes and composite word schemes. In C++, keywords and standard library identifiers are mostly lowercase. C++ mostly uses underscore( _ ) as a word separator. Identifiers representing macros are written in upper case letters and underscores.

Comments and Documentation

Starting with a formal definition , “In programming, comments are self explanatory statements which are intended to imply the meaning of any block written in the source code which can help anyone to read your source code and draw inference regarding the code block or the role, it plays inside the algorithm being implemented by the source code”.

In short, writing the real objective of any code being written in a file. These lines or comments are treated as insignificant portions of the source code file and are ignored by the compiler or interpreter. There are two major ways to put documentation in a C++ file.

  • Multiline Documentation or prologue documentation which starts with /** and ends with */ . Therefore this how the multi line commented blocks or statements appear –
    /**statements
    ----------------------
    ----------------------
    */
    
  • Single line Documentation or Inline Documentation which starts with // and is used in the following manner –
    int a = 5; // the variable a is initialized with 5
    

Document-able or comment-able code blocks in C++ are –

  • Classes
  • Structures
  • Unions
  • Enums
  • Functions
  • Statements
  • Variables
  • Macros
  • Conditionals

So now, we will say hello to the world again and this time with proper comments which will make it look professional as well as formal 😛

#include
/*The name of the function is main
*It is the driver function of the code
*/

int main()   // Main function signature
{   // function body starts
cout << "Hello World. I am from theoryofprogramming.com"; /* cout is output stream object responsible for printing hello world on the display peripheral */
return 0;
// function body ends
}

So, the above code has a very bad comment, adjacent to the cout statement just because of two reasons –

  • A multiline comment in order to explain a single statement is overarching.
  • The comment is too long enough and deviates the attention unnecessarily.

Now this is something poetic and I believe every programmer is a poet. So, I leave on you to think what can be an appropriate comment for that “cout” statement 😀
The most important part and generally arises from the mind of cryptic programmers. “Nested Comments”. Well personally, I do not prefer it because I can hardly think of any circumstance where it might be needed. Nested Comments can be thought of as –

/*This is theoryofprogramming.com
//welcome readers */

Or

//This is a /*legal comment*/ from theoryofprogramming.com

Or

/*This is a legal comment /*nested comment */ from theoryofprogramming.com*/ :p

The first and second one looks absolutely good and can be treated as nested comments. But what about the third one. Imagine, if you were a compiler and you have been told to parse the third statement character by character. You would have thought in the following manner –

  • Encountered a “/*” token. My comment is going to start from this point.
  • You continue to ignore every character that you face after it.
  • As soon as you get a “*/” together , you think that this is the end of the statement.

This is exactly what happens and you end up hard coding a line “from theoryofprogramming.com*/” which the compiler treats as a piece of code and tries to compile it and congratulations you receive a compiler error!! So nested comments are confusing to use although the modern IDEs does not allow us to commit such a mistake but still nested comments are an absolute nightmare and that is why C++ forbids the use of nested comments. Obviously it eases out the parsing for the languages and I find this absolutely well as a programmer too. However, if you already got a multi line comment in a code block that you want to comment out. You can make the compilers optimize away the fact, by surrounding it with #if 0 . This is just a trick and does not need any special attention. This is how it is done.

#if 0
/*

*/
endif

In short, three words i.e indentation, documentation and variable naming . These three things are very important for a programmer to first realize their utilities and then make use of them in a sincere manner. Two important points which one should always keep in mind while using these words: brevity and clarity. Hope of you have a nice day. Enjoy and write beautiful codes. 🙂

C++ – Variables, Initialization and Assignment

So, let’s bring in, the concept of Al – Jabr from the school mathematics at this point. From Al- Jabr (you guessed it right, Algebra it is 😛 😀 ), the concept of variables came into action, using which a set of values or numbers are represented. Now from the programming point of view, these variables are used more or less for the same purpose, indirectly. The difference lies in the fact that the variables used here are responsible for representing a chunk or a block of memory which in turn serves as a storage location for a set of values or numbers.
Two pretty obvious questions which arise:-

  1. Where are these variables stored?
  2. How do we implement it in C++?

Obviously, these variables in the running state of program are stored in RAM, to be more specific, maybe a stack or heap or data segment which we will be discussing later on in the succeeding articles and when it is saved, a copy of it is stored in the secondary storage.
Before answering questions, I would like to bring into light the concept of data types without which the variables cannot be implemented. The fact is that the compilers are actually not smart enough as we expect. We always need to explicitly mention the type of data which it will be storing, beforehand so that it is ready with the necessary amount of memory block allocations which the variables might require. Our data or value could be anything an integer, a character, a decimal number and many more…. Thus, there is a pretty obvious need to mention the type of data which the compiler might expect, to be stored inside a variable.
In order to declare a variable, we generally used a declarative statement such as

int x; -----> declares an integer
char c; ----> declares a character

Now, as the compiler encounters these statements, a block of memory is kept apart for it. This process is known as instantiation. Although ISO C++ 11 introduces a syntactic sugar in order to deal with the explicit mention of data types, which will be a suspense till the upcoming articles are published 😛 😀

Assignment

Let us consider a declarative statement:-

int x;

Now, we want to put in a value to x at any point of program or code. The process of assigning a particular value to a variable at any point of a program or code due to the demand of the logic of the program is known as an assignment operation. Since we declared the variable x above, now we can perform assignment operation on it in the following manner.

x = 10;

Initialization

C++ also allows defining and giving an initial value to a declared variable in the same statement. This process is known as initialization. Basically this process denotes that there is variable which will be starting off its life with an initial value stored in it. A variable can be initialized only when it is defined. Following statement illustrates the use of initialization.

int x = 19;

Here the variable starts off with the value 19.

Initialization and assignment? Same thing??

Well, according to the definition stated above, these two things are different. But to the beginners, this might appear similar in technique. But there is a suspense, which will be revealed later in the upcoming articles as to how they serve to be different. Not only that, there are some type of values which will only support initialization and not an assignment. Therefore, from today, it is to better to have a mindset that these two things are significantly different. 🙂

Now coming to CBSE board’s favorite question 😛 and an interviewer who might also expect an answer to this question…

l-value and r-value

An l-value is a value that has an address……… Address?? 221-B Baker Street…. No not at all 😀
An l- value is a value that has an address in memory i.e a value that points to storage location. One such thing which we discussed earlier in this article is a “variable”. So you guessed it right, a variable is a kind of l-value. In assignment operation, the left hand side operand of the assignment operator must always be an l-value. In a similar opposite manner, rvalue is something which must result to a single valued character, integer, or any other type of data and these values do not have an address in memory. They are just mere values which may also result from expressions. Let us consider an example.

int a = 5; ------> This is initialization
int b; ----------> This is declaration
b = 6; ----------> This is assignment

Assignment in C++

Uninitialized variables

Uninitialized variables are those variables where which have not been initialized with a value. Unlike many programming languages, C++ does not initialize variables with a default value such as 0. As soon as the variable is assigned a memory location, a garbage value is dumped into that location. Let us look at a code to get an essence of the above fact

#include<iostream>
int main()
{
	int a;
	std::cout<<a;
	return 0;
}

So what output do you expect 😛 . Even I do not know what I will be getting in this case. The answer will be given by the compilers and their configurations and the answer is not at all obvious. Every time you might get different answers or maybe a same bogus answer. I use GCC 4.7.2 32 bit release with –std switch set as ISO C++ 11 and the answer I get is 4285790. In Microsoft Visual C++ we get different garbage values when we are in release configuration of build environment. Basically, we do not give a damn as to what we are getting. The point is uninitialized variables are signs of bad programming practices. Beginners, please keep a note of this because when you start writing complex programs, there will be situations where you might scratch your head regarding the results and ultimately banging your head. Finally, you will end up hardcoding to avoid those erroneous situations. Just a favorite comic to make u realize the fact I have one comic page for you. :P.

2010-04-09-programmer_grief
So, embed in your reflexes to initialize the variables resulting in a consistent state and a one which will be easier to debug 🙂 ….. So Congratulations to you again … You learned something new. Time to party. 😛

Why should I learn C++?

Hello folks, this is Punit Sharma from theoryofprogramming.com. Good morning, afternoon or evening accordingly, at whatever time you visit this article. So in this article, I will be providing you an essence of the C++ programming language and why you should use it or rather learn it.
First off, the name. You might be wondering what that “++” is doing there in the name. In many programming languages, ++ is an increment operator. So, C++ is meant to be the next version of C. Well, C++ language is always something that has been viewed as a cryptic programming language. It might sound as a huge understatement but many people are afraid to use or learn C++ just because of the fact that it is vast, and the concepts are too tough to cooperate with. So writing this article serves to be a clear intention to remove this rumor and helping you to use this language because it is beautiful, and will become more beautiful as soon as you get used to it. So let us define C++ in the words stated by its inventor –

“A light-weight abstraction programming language designed for building and using efficient and elegant abstractions and offering both hardware access and abstraction. Doing it efficiently is what distinguishes it from other languages…”       – Sir Bjarne Stroustrup

So Stroustup’s intentions were pretty clear in the above statement. So how many of you agree to what was stated above?
The novice programmers or the ones who are acquainted with Java or C# as the only language in their life might find this statement least interesting. But trust me as well as Bjarne Stroustrup, this programming language brings to you object oriented programming in a taste which you never had with Java or C# when you learnt it for the first time.

How C++ is better?

Getting into insights of the language, the inbuilt sorting function of C++ uses Introsort which is a type of hybrid sorting algorithm (Hybrid of Quicksort and Heapsort) followed by an Insertion Sort on the result. In practical scenarios, in a coding competition, this sort function always serves as a better one than the sorting functions of other object-oriented languages. Let me show an illustration of this. Consider the problem given in the following CodeChef link – https://www.codechef.com/problems/DONUTS.

You can see the rankings with the image below –

C++ in Competitive Programmingcodechef_rank2
 

This problem requires sorting of data at a certain point of the algorithm. And the top 15 submissions are either in C (26.77%) or C++ (73.33%). Moreover, the ones which are submitted in Java or any other language have a worse time and space factor. So C++ provides an extra edge from a competitive programming point of view as well.

Another performance factor where C++ serves as a better option than other OOP languages is in a scenario where objects are being created and destroyed in a loop running in order of 106 or greater than that. Although C++ needs manual allocation and deallocation of memory, it properly deallocates the memory at a good rate in the above situation whereas OOP languages like Java which boasts regarding automatic garbage collection have a garbage collector thread which performs very slowly.
Thus, memory allocations are being done at a faster rate and the rate of destruction being slower. Thus, any scenario like this will result in what we know as “Memory Limit Exceeded”….

Believe it or not, the giants in the gaming industry rely heavily upon C++. Video games still use C++. One example is the Torque engine which can be used for iPhone and Xbox game development. Another reason why this language is great – it is really cross-platform. It is used almost everywhere – PC, Mac, Xbox 360, PS3, cell phones, embedded… you name it. So you can use your skills on almost any platform you feel like. As opposed to many other languages, which are often only useful for one platform. So any aspirant of EA Sports, Nintendo, Sega, Ubisoft etc. should possess proficient skills in language and is a necessity while you submit a resume at this companies.

Not only that, advanced audio and image processing engines use C++. C++ is still used extensively for performance-intensive tasks. For example, a lot of work with video compression and decompression – it’s all C++. Partly because we need the performance, and partly because all the 3rd party libraries which need to use are C++. So it’s easier to integrate with them if we’re using the same language. C++ also leads to a good heat in your pocket or salary++ (the experts say) even if you work with a corporate powerhouse that does not work with the language. Bloomberg, Reuters, and all their bank/trading clients who want low latency market data feeds use C++.
Huff!!!!!! So enough of bragging done….! Hopefully, I was able to justify using the above facts that why C++ should exist and should be learnt and appreciated. There are other facts and features which you will definitely learn and understand in the upcoming articles and get lost in the beauty of C++. Some favourite quotes of mine by Sir Bjarne:-

  • C++ is my favourite garbage collected language because it generates so little garbage.
  • C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.