Creating Basic C++ Elements

Discussion in 'C++' started by BiplabKamal, Apr 30, 2016.

  1. In the first chapter we have seen what are the minimum elements a program should have. In this chapter we will learn to create those basic elements and give the shape of a basic program which can be compiled using C++ compiler. You can create a program which will silently do some task but you will not see any result. So any program will have the functionality of publishing it's result. Also most of the programs will take input from user or other external entity. We will restrict our program in this chapter to take input from the user via console and display result on the console. Reading input from the console and writing to the console are not part of the language specification but C and C++ provides some already created functions which can be called to accomplish those input-output operations. These helper functions are called library functions. Declaration of these functions are required to be included during compilation and compiled definitions need to be available during linking (linking is a sub step of the compilation process). We will only use helper functions which are part of the C language and also valid for C++.

    Creating Variables and Constants

    In the first chapter I said that variables are used to create data storage. Variables are placeholders for data. Variables have name, meaning and size. Meaning of a variable is indicated by it's type. Type of a variable indicates the meaning(interpretation) and the size (number of bytes required to store the data). There are two types : inbuilt types and user defined types. Inbuilt types are specified by language defined key words. User defined types are created by the programmer. In this chapter we will confine our discussion with inbuilt types only.

    Suppose we want to store an unsigned integer number which can be stored in 4 bytes of memory. This implies that in this data store we can store a number in the range of 0 to 232-1. Let us give the name of the variable 'Number1'. The key word available for the said type is 'unsigned'. Following line of text (called source code) will create the variable mentioned above. Same line of code is used to declare and define the variable.

    unsigned Number1;

    Above line of code reserves a data storage. The code has three parts in it:
    1. Data type: 'unsigned' is a predefined data type defined by the language. When compiler see this keyword it knows the meaning and storage size of the data. 'unsigned' means unsigned integer and size is 4 bytes
    2. Data Name: 'Number1' is used to refer this piece of data
    3. Line ending symbol: ';' is used to end a complete statement. ';' marks the end of both data declaration/definition statement and instruction statement.
    Now if you want to create an unsigned integer data of size 5 bytes, is that possible? Unfortunately no. C++ allows only predefined elementary data types and each data type has fixed meaning and size. There is no data type available of for unsigned integer of size 5 bytes. You are restricted to use only a fixed list of data types defined by the language specification. Following are some of the in-built data types in C++:


    There are many more data types but we will not go behind each of them because that will not help us at this point. We will discuss them when needed.

    Let us go to our discussion point which is creating variables. We have just declared and defined the variable 'Number1' but we have not stored any value. Remember that the declaration and definition are done in the same statement. So we will just call it definition. You can declare a variable in one file and define it in another file. Actually for compilation only declaration is enough but for linking definition is needed. Until you define some thing it does not allocate the storage. Now we want to store some value in 'Number1'. This requires an executable statement which can be written in a function only. Assignment statement is used to assign a value to a variable as shown below:

    Number1 = 100;

    '=' is an arithmetic operator in C++ like many other languages which is used to store a value in a variable. C++ has many arithmetic and other operators which we will declare in later point of time. The compiler will allow only to assign positive numbers or the values which can be safely converted to positive numbers. Again if you assign a value which is in the out of range it will be truncated. So when you assign a value you should know what is actually stored. C and C++ is flexible enough to type cast implicitly to allow the bugs remain undetected. The compiler may give warning but that may not be enough.

    So far we have written 2 lines (statement) of code to store a numerical value in a variable. We could do that in a single statement as shown below which can be done outside any function also.

    unsigned Number1{100};

    This is called variable initialization. Assigning value while defining the variable is called initialization. Normally initializing is used to store the default value, otherwise the initial value will be undefined or junk.

    Now we talked about variables whose value can be changed whenever we want. Following lines of code is valid within a function.
    unsigned Number1 = 100;
    Number1 = 200;
    Number1 = 300;
    But sometimes we need to define a data which only can be given initial value but cannot be changed later. This are constant variables or just called constants. So for constant variables we can only initialize while defining but cannot assign value later. This is done by applying a qualifier called 'const' which is again a keyword. Here is the syntax:
    const unsigned Number2 = 100; //Defining a variable 'Number2' with initial value 100
    Number2 = 200; //Not allowed for constant variable
    There is also another qualifier called 'constexpr' which also define a constant variable but the value assigned must be a constant expression which is not true for 'const' qualifier. Following lines of code will resemble the difference. Please note that text after the '//' symbol is comments and not treated as part of the code.
    	unsigned Number1 = 100;
    	const unsigned Number2 = Number1; // Valid
    	constexpr unsigned Number3 = Number1; // Not valid because right side of the assignment operator should be a constant number or another constexpr
    	constexpr unsigned Number4 = 100;// Valid
    Now we know how to write statement to create variables. We haven't seen how to create executable instructions to specify program logic. Executable statements can be present only inside a function body. So we will look into the syntax of functions.

    Creating Functions

    A function has a name, return type, arguments and body. Name, return type and arguments are specified in the declaration and the body is part of the definition. Similar to data definition, function definition also implies the declaration if you don't provide the declaration separately. Declaration is mandatory if you want to invoke the function where the definition is not visible. Suppose we want to create a function which will take two integer number and give the addition result of the numbers. So the function will have two arguments of integer type and return type as integer for returning the result. Let us name the function as 'Add'. The declaration statement for the function

    int Add(int, int);
    The above declaration matches with the syntax : <return type><function name>(<return type of arg1>, <return type of arg2> … ). There can be 0 or more arguments and may not return anything. Argument types are separated by comma(,) . If we want to declare a function which will not take any input and will not return anything but do some data manipulation the function declaration is shown below. Let us give the name 'DoSomething'.
    void DoSomething();
    The 'void' key word says that it returns nothing. The declaration also is called prototype or signature. The definition of a function contains the signature followed by a sequence of statements enclosed with curly braces({}). Statements consists of variable definitions and executable statements. Now we will define the Add function we declared above. The arguments of a function becomes variables inside the function and visible in the function only. We need to give argument names in the definition but in case of declaration the name of argument is optional. In the body we will create another variable 'result' of type integer. This variable will store the sum of the two argument's values sent by the caller and then return the result value to the caller. Here is the code:
    int Add(int number1, int number2)
    	int result =0; //Definition with initialization
    	result = number1 + number2;
    	return result;
    In the above code we use another arithmetic operator '+' to add the values of two variables.

    Naming Rules

    Naming a variable or a function has some rules to follow. You can not use arbitrary symbols in the variable or function names. The rules also applies to other names like class names, structure names, enumerator names etc.). These names are called identifier in C++ and has common rules outlined below:
    1. Identifiers are case sensitives. So lower case letters and upper case letters are different
    2. An identifier can not begin with a digit.
    3. Identifiers can have only alphabet, digits and underscore (_).
    4. Other special characters including space and punctuation marks are not allowed
    5. Identifiers cannot match the keywords defined by the language
    For example:
    • 'Number1' is valid identifier.
    • 'Number 1' is not valid identifier because space is not allowed.
    • '1Number' is not valid identifier because it begins with a digit.
    • 'Number-1' is not valid identifier because special character '-' (hi-fen) is not allowed.
    • 'class' is not valid identifier because it is a keyword.
    • 'Class' is a valid identifier because 'class' and 'Class' are different
    Now we have the initial idea about how to create a function with data and instructions. We also know that variables can be declared either in a function or outside any function. Variables declared out side a function is available for all functions to use, hence is called global variables. Variables declared inside a function is available only to the same function, hence is called local variables. We know that executable statements can only be written within a function. The Add function created above is just one function which does a specific task. For a complete program we may need more than one function among which one function will work as starting function or entry function. Entry function will call other functions to complete the overall task of the program. Most of the programs will interact with user. Let us now consider the whole application which will take two numbers from the user and display the sum of the numbers to the user. We will use console window which is a command line window for user interaction. We will use the Add function defined above(). To get input numbers from user and display the result we will use two helper functions printf() and scanf() from C standard library. The library functions are compiled version comes with C++ compiler. We need to include the declaration of the functions while compilation and the definition need to be available during linking. Declaration of those input output functions are given in a file name 'stdio.h' and definition in compiled form is available in standard library files include by the conpiler. To include the declaration you have to use #inlcude statement. Here is the complete program-

    #include<stdio.h> //Include header file
    //Following function will add two numbers and give the result
    int Add(int number1, int number2)
    	int result =0;
    	result = number1 + number2;
    	return result;
    unsigned inputnumber1{ 0 }; // Variable to hold the first input number from the user
    unsigned inputnumber2{ 0 }; // Variable to hold the second input number from the user
    void UIFunction()
    	printf("Enter the first number: "); // Print the message to enter the first number
    	scanf("%d", &inputnumber1); // Read the first number given by the user
    	printf("\nEnter the second number: "); // Print the message to enter the second number
    	scanf("%d", &inputnumber2);// Read the second number given by the user
    	int sum = Add(inputnumber1, inputnumber2); // Call the Add function and hold the returned result
    	printf("The Sum of the two numbers = %d\n", sum); // Display the result
    To run the program you have to compile the program specifying that 'UIFunction' is the entry function or create another function as entry function which will call 'UIFunction'.

    In the next chapter we will discuss compilation and linking in detail.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice