Pointer Definition in C++

, ,

For a C++ program, computer memory is like succession memory cells, each holding one-byte size and having a unique address. Dealing with these memory addresses in programming is done by pointers. Pointers are extremely powerful programming tool that can make things easier and help to increase the efficiency of the program and allow programmers to handle the unlimited amount of data. It is possible for pointers to dynamically allocate memory, where programmers don’t have to worry about how much memory they will need to assign for each task, which cannot be done/performed without the concept of the pointer. Hence pointer is considered as the most distinct and exciting feature of C++ language which adds power as well as flexibility to the language. In other words, a pointer variable holds the address of a memory location.

Pointer Definition in C++

Syntax:
type *variable_name;
Example:
int  *height;char  *age;



Benefits of using Pointers in C++

  • Pointers save the memory.
  • Pointers reduce the length and complexity of the program.
  • Pointers allow passing of arrays and strings to functions more efficiently.
  • Pointers make possible to return more than one value from the function.
  • Pointers increase the processing speed.

How to use Pointers in C++

Example:
#include <iostream>using namespace std;int main (){   int  n = 20, *ptr;  /* actual and pointer variable declaration */   ptr = &n;  /* store address of n in pointer variable*/    cout << "Address of n variable: " << &n << endl;      /* print address stored in pointer variable */   cout << "Address stored in pntr variable: " << ptr << endl;   /* print access the value using the pointer */   cout << "Value of *pntr variable: " << *ptr << endl;      system("pause");   return 0;}




Loops in C++

, ,

Sometimes it is necessary in the program to execute the statement several times, and C++ loops execute a block of commands a specified number of times until a condition is met. In this post, you will learn about all the looping statements of C++ along with their use.

Loops in C++

There may arise some situations during programming where programmers need to execute the block of code several times (with slight variations sometimes). In general, statements get executed sequentially with a C++ program, one statement followed by another. C++ provides statements for several control structures along with iteration/repetition capability that allows programmers to execute a statement or group of statements multiple times.

C++ supports following types of loops:
  • while loops
  • do while loops
  • for loops





All are slightly different and provides loops for different situations.

Figure – Flowchart of Looping:

akhtarbari.com

C++ Loop Control Statements

Loop control statements are used to change the normal sequence of execution of a loop.

StatementSyntaxDescription
break statementbreak;Is used to terminate loop or switch statements.
continue statementcontinue;Is used to suspend the execution of current loop iteration and transfer control to the loop for the next iteration.
goto statementgoto labelName;labelName: statement;It transfers current program execution sequence to some other part of the program.




COPY CODE SNIPPET

Decision Making in C++

, ,

C++ conditional statements allow you to make the decision, based upon the result of a condition. These statements are called as Decision Making Statements or Conditional Statements.

So far, we have seen that all set of statements in a C++ program gets executed sequentially in the order in which they are written and appear. This occurs when there is no jump based statements or repetitions of certain calculations. But a number of situations may arise where we may have to change the order of execution of statements depending on some specific conditions. This involves a kind of decision making from a set of calculations. It is to be noted that C++ assumes any non-zero or non-null value as true and if zero or null, treated as false.




This type of structure requires that the programmers indicate several conditions for evaluation within a program. The statement(s) will get executed only if the condition becomes true and optionally, alternative statement or set of statements will get executed if the condition becomes false.

The flowchart of Decision-making technique in C++ can be expressed as:

akhtarbari.com

C++ languages have such decision-making capabilities within its program by the use of following the decision making statements:


Decision Making Statements in C++



What are the Functions in C++

, ,

As we all know functions play an important role in programming. Driving programs into functions is one of the major principles of programming. In C, they are called functions but in C++ they are termed as member functions. In this tutorial you will learn about the member function and its concept used in C++

What are Member Functions in C++?

Member functions are C++ functions that have their declarations inside the class definition and these member functions work on the data member of the class. Member function definition can be written inside or outside the definition of the class. If the definition of member function is inside the class definition, then it can e defined directly, but if it is defined outside the class then a special operator name scope resolution operator (::) is used along with the name of the class and the function name.

Example:
class Sq {public:    int a;    int square(); // Declaring function square with no argument and having return type 'int'.};int Sq::square(){    return a * a;}

In this case, if you define the member function outside the class definition, then you must declare the function inside class definition and then define it outside using the scope resolution operator.

or

Example:
class Sq {public:    int a;    int square()    {        return a * a; //returns square of a number    }};

In the above program, the function is defined inside the class and so you do not need to declare it first and can directly define the function.

main() Function of C++

The main() function is called when the program starts after initialization of the non-local objects with static storage duration. It is the primary entry point of any C++ program that is executed in the hosted environment. In C++, the main() function is written after the class definition. The main function of C++ has several special properties. These are:

  1. main() function cannot be used anywhere within the program
    1. In particular, cannot be called recursively
    2. Its address cannot be taken for reuse
  2. main() function cannot be predefined and cannot be overloaded.
  3. main() function cannot be declared as static, inline or constexpr
  4. The return type of the main() function cannot be deduced (i.e. auto main() {… is not allowed in C++).

The main() function for both the function definition (discussed above) will be same. You have to create objects of the class inside the main() and using that object along with the dot (.) operator member functions will be called.

Syntax:
return_type main(){    class_name object - declaration;    object_name.memberfunction1_name();    object_name.memberfunction2_name();    ........}
Example:
int main(){    Sq S1;    S1.a = 6;    S1.square();    cout << " Square of the number is :"<< S1.square();}

Types of Member Functions in C++

As we are now familiar with what are member function and how they are declared and defined, how they are used in a C++ program to handle data member and member functions, and how they are called from the main(); it is time to know what are the different types of member function provided by C++.

Listed below are the special types of member functions that can be used within the class.
  • Simple member function
  • Static Member function
  • Const function
  • Inline function
  • Friend function

Simple Member Functions

As discussed earlier, these are simple functions of C++ with or without return type and with or without parameters. The basic structure of a simple member function is:

Syntax:
return_type functionName(parameter_list){    // function body;}



Static Member Functions

The keyword ‘static‘ is used with such member functions. Static is mainly used to hold its positions. These functions work for the whole class rather than for a particular object of the class.

Example:
class X {public:    static void k(){};};int main(){    G::k(); // calling member function directly with class name}

The static member functions cannot access ordinary data members and member functions, but can only access the static data members and static member functions of a class.

Const Member Function

Const keyword makes variable constant, which means once defined, their value cannot be changed. The basic syntax of const member function is:

Example:
void fun() const{}


Inline Function

When a function is declared as inline, the compiler places a copy of the code of that specific function at each point where the function is called at compile time.

Friend Function

Functions are declared as the friend using the keyword ‘friend’ to give private access to non-class functions. Programmers can declare a global function as a friend, or a member function of other class as a friend.

Storage Classes in C++

, ,

The storage class is used to specify control two different properties: storage life-time and scope(visibility) of variables.

Following storage classes can be used in a C++ Program:
  • Automatic
  • External
  • Static
  • Register

Automatic(auto) Storage Class

Variable defined within the function body are called auto variable. The auto storage class is used to declare automatic variables, which is also called local variables.

Example:
auto int a, b, c = 100;

is same as:

int a, b, c = 100;



The External Storage Class

External variables are defined outside of the function. Once External variable declared, the variable can be used in any line of codes throughout the rest of the program.

The extern modifier is most commonly used when there are two or more C++ files sharing the same global variables or functions.

First File : main.cpp

Example:
#include <iostream>#include "file.cpp"int count ;extern void write_extern(); main(){   count = 5;   write_extern();   system("PAUSE");}

Second File : file.cpp

Example:
#include <iostream>extern int count; void write_extern(void){   std::cout << "Count is " << count << std::endl;}




Data Types available in C++

, ,

Data types in any of the language mean that what are the various type of data the variables can have in that particular language. Information is stored in a computer memory with different data types. Whenever a variable is declared it becomes necessary to define the data type that what will be the type of data that variable can hold.

Data Types available in C++:
  1. Primary(Built-in) Data Types:
    • character
    • integer
    • floating point
    • boolean
    • double floating point
    • void
    • wide character
  2. User Defined Data Types:
    • Structure
    • Union
    • Class
    • Enumeration
  3. Derived Data Types:
    • Array
    • Function
    • Pointer
    • Reference





Both C and C++ compilers support the fundamental i.e. the built-in data types. Taking void as exception, the basic data types may have several modifiers, and these modifiers are used to serve the data types in various situations.

The lists of modifiers used in C++ are:
  • signed
  • unsigned
  • long
  • short

Character Data Types

Data Type (Keywords)DescriptionSizeTypical Range
charAny single character. It may include a letter, a digit, a punctuation mark, or a space.1 byte-128 to 127 or 0 to 255
signed charSigned character.1 byte-128 to 127
unsigned charUnsigned character.1 byte0 to 255
wchar_tWide character.2 or 4 bytes1 wide character

Integer Data Types

Data Type (Keywords)DescriptionSizeTypical Range
intInteger.4 bytes-2147483648 to 2147483647
signed intSigned integer. Values may be negative, positive, or zero.4 bytes-2147483648 to 2147483647
unsigned intUnsigned integer. Values are always positive or zero. Never negative.4 bytes0 to 4294967295
shortShort integer.2 bytes-32768 to 32767
signed shortSigned short integer. Values may be negative, positive, or zero.2 bytes-32768 to 32767
unsigned shortUnsigned short integer. Values are always positive or zero. Never negative.2 bytes0 to 65535
longLong integer.4 bytes-2147483648 to 2147483647
signed longSigned long integer. Values may be negative, positive, or zero.4 bytes-2147483648 to 2147483647
unsigned longUnsigned long integer. Values are always positive or zero. Never negative.4 bytes0 to 4294967295



Floating-point Data Types

Data Type (Keywords)DescriptionSizeTypical Range
floatFloating point number. There is no fixed number of digits before or after the decimal point.4 bytes+/- 3.4e +/- 38 (~7 digits)
doubleDouble precision floating point number. More accurate compared to float.8 bytes+/- 1.7e +/- 308 (~15 digits)
long doubleLong double precision floating point number.8 bytes+/- 1.7e +/- 308 (~15 digits)

Boolean Data Type

Data Type (Keywords)DescriptionSizeTypical Range
boolBoolean value. It can only take one of two values: true or false.1 bytetrue or false



Below example will produce correct size of various data type, on your computer.

Example:
#include <iostream>using namespace std;int main() { cout << "Size of char is " << sizeof(char) << endl; cout << "Size of int is " << sizeof(int) << endl; cout << "Size of float is " << sizeof(float) << endl; cout << "Size of short int is " << sizeof(short int) << endl; cout << "Size of long int is " << sizeof(long int) << endl; cout << "Size of double is " << sizeof(double) << endl; cout << "Size of wchar_t is " << sizeof(wchar_t) << endl; return 0;}
Program Output:
Size of char is 1Size of int is 4Size of float is 4Size of short int is 2Size of long int is 4Size of double is 8Size of wchar_t is 4

Enum Data Type

This is an user defined data type having finite set of enumeration constants. The keyword ‘enum‘ is used to create enumerated data type.

Syntax:

enum enum-name {list of names}var-list;
enum mca(software, internet, seo);

Typedef

It is used to create new data type. But it is commonly used to change existing data type with another name.

Syntax:

typedef [data_type] synonym;

or

typedef [data_type] new_data_type;
Example:
typedef int integer;integer rollno;

Operator in C++

, ,

C++ operator is a symbol that is used to perform mathematical or logical manipulations. C++ language is rich with built-in operators.

Arithmetic Operators

OperatorDescription
+Addition
Subtraction
*Multiplication
/Division
%Modulus

Increment and Decrement Operators

OperatorDescription
++Increment
−−Decrement

Relational Operators

OperatorDescription
==Is equal to
!=Is not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical Operators

OperatorDescription
&&And operator. Performs a logical conjunction on two expressions.
(if both expressions evaluate to True, result is True. If either expression evaluates to False, result is False)
||Or operator. Performs a logical disjunction on two expressions.
(if either or both expressions evaluate to True, result is True)
!Not operator. Performs logical negation on an expression.




COPY CODE SNIPPET

Bitwise Operators

OperatorDescription
<<Binary Left Shift Operator
>>Binary Right Shift Operator
~Binary Ones Complement Operator
&Binary AND Operator
^Binary XOR Operator
|Binary OR Operator

Assignment Operators

OperatorDescription
=Assign
+=Increments then assigns
-=Decrements then assigns
*=Multiplies, then assigns
/=Divides then assigns
%=Modulus then assigns
<<=Left shift and assigns
>>=Right shift and assigns
&=Bitwise AND assigns
^=Bitwise exclusive OR and assigns
|=Bitwise inclusive OR and assigns

Misc Operators

OperatorDescription
,Comma operator
sizeof()Returns the size of a memory location.
&Returns the address of a memory location.
*Pointer to a variable.
? :Conditional Expression




What are Constants in C++?

, ,

What are Constants?

Constants are like a variable, except that their value never changes during the program execution once defined. Constants refer to as fixed values, unlike variables whose value can be altered, constants – as the name implies does not change, they remain constant. Constant must have to be initialized at the time of creating it and new values cannot be assigned later to it.

Constant Definition in C++

There are two other different ways to define constants in C++. These are:

  • By using const keyword
  • By using #define preprocessor

Constant Definition by Using const Keyword

Syntax:
const type constant_name;
Example:
#include <iostream>using namespace std;int main(){  const int SIDE = 50;  int area;  area = SIDE*SIDE;  cout<<"The area of the square with side: " << SIDE <<" is: " << area << endl;  system("PAUSE");  return 0;}

 


It is also possible to put const either before or after the type.

int const SIDE = 50;

or

const int SIDE = 50;

Constant Definition by Using #define preprocessor

Syntax:
#define constant_name;
Example:
#include <iostream>using namespace std;#define VAL1 20   #define VAL2  6#define Newline '\n'int main(){   int tot;    tot = VAL1 * VAL2;   cout << tot;   cout << Newline;}



What are Tokens in C++

, ,

What are Tokens

Each individual word and punctuation is referred to as a token in C++. Tokens are the smallest building block or smallest unit of a C++ program.

These following tokens are available in C++:





Identifiers: Identifiers are names given to different entries such as variables, structures, and functions. Also, identifier names should have to be unique because these entities are used in the execution of the program.

Keywords: Keywords is reserved words which have fixed meaning and its meaning cannot be changed. The meaning and working of these keywords are already known to the compiler. C++ has more numbers of keyword than C and those extra ones have special working capabilities.

Operators: C++ operator is a symbol that is used to perform mathematical or logical manipulations.

Constants: Constants are like a variable, except that their value never changes during execution once defined.

Strings: Strings are objects that signify sequences of characters.


C++ Keywords List

, ,

C++ Keywords List

The C++ Keywords must be in your knowledge because you can not use them as a variable name.

You can’t use keyword as identifier in your C++ programs, its reserved words in C++ library and used to perform an internal operation.

asmelsenewthis
autoenumoperatorthrow
boolexplicitprivatetrue
breakexportprotectedtry
caseexternpublictypedef
catchfalseregistertypeid
charfloatreinterpret_casttypename
classforreturnunion
constfriendshortunsigned
const_castgotosignedusing
continueifsizeofvirtual
defaultinlinestaticvoid
deleteintstatic_castvolatile
dolongstructwchar_t
doublemutableswitchwhile
dynamic_castnamespacetemplate




In addition, the following keywords are also reserved:

Andbitornot_eqxor
and_eqcomplorxor_eq
bitandnotor_eq