Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of const keyword with pointers

    • 0
    • 4
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 247
    Comment on it
    //=============   A simple program to demonstrate the use of "const" keyword with pointers==================
    /*
    *    By => Bipin Gosain
    *    Date => 17/4/2016
    */
    #include <iostream>
     
     int main(){
         using std:: endl;
         using std:: cout;
         //========= Part I ===========
         /*
             int data = 100;
             const int *pointerToAConstValue = &data;//A pointer to a constant value
            *pointerToAConstValue = 1;//Error 
             data = 1;//No error
         */
         //========= Part II ===========
            /*
            const int data = 100;//constant value
            const int *pointerToAConstValue = &data;//A pointer to a constant value
            *pointerToAConstValue = 1;//Error 
            data = 1;//Error
            */
        //========= Part III ===========
            int data = 100;//constant value
            int anotherVariable = 200;
            int * const pointerToAConstValue = &data;//A constant pointer ...it can't point to any other location(Address)
            *pointerToAConstValue = 20;//No Error
            cout << "value at pointer "<< *pointerToAConstValue << endl;
            data = 1;//No Error
            cout << "value at pointer "<< *pointerToAConstValue << endl;
            pointerToAConstValue = &anotherVariable;//Error
         
     }

    Following program is to demonstrate the use of const keyword with pointers:

    PART I : shows  the pointer to a constant value which can't be changed by the pointer but can be changed directly.

    PART II : shows a constant value being pointed which cannot be changed by the pointer or directly.

    PARTIII : shows the use of constant pointer which cannot point to any other variable expect to which it is pointing.

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: