Answer to Question #184117 in C++ for Uzair Ali

Question #184117

Write small programs to demonstrate the behavior of the constant variable, 

constant pointer, constant pointer to constant variable and passing constant 

pointer to the function. 


1
Expert's answer
2021-04-24T15:14:01-0400
#include <iostream>

int main()
{
 
    int nonConstVariable{ 5 };
    int nonConstVarible2{ 6 };
    const int constVariable{ 5 };
 
    //// A non-const pointer can be redirected to point to other addresses.
    int* pointer{ &nonConstVariable };
    pointer = nullptr;
 
    pointer = &nonConstVarible2;
    pointer = nullptr;
 
    //// A const pointer always points to the same address, and this address can not be changed.
    int* const constPointer{ &nonConstVariable };
    // constPointer = nullptr; // can't point to diffrente address even nullptr?
    *constPointer = 10;        // works, because it can change the value at the given address but not the address itself
    delete constPointer;
 
    //// A pointer to a non-const value can change the value it is pointing to. These can not point to a const value.
    pointer = &nonConstVarible2;
    // pointer = &constVariable; // can't point the non-const pointer to the const value?
 
    //// A pointer to a const value treats the value as const (even if it is not), and thus can not change the value it is pointing to.
    const int* const constPointer2{ &constVariable };
    // *constPointer2 = 15; // l-value must be modifiable value (constVariable isn't modifible l-value) it's constant
    
    delete pointer;
 
 
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS