C++ const keyword

Question 1
Predict the output of following program
#include <iostream>
using namespace std;
int main()
{
    const char* p = "12345";
    const char **q = &p;
    *q = "abcde";
    const char *s = ++p;
    p = "XYZWVU";
    cout << *++s;
    return 0;
}
Cross
Compiler Error
Tick
c
Cross
b
Cross
Garbage Value


Question 1-Explanation: 
Output is ‘c’ const char* p = “12345″ declares a pointer to a constant. So we can’t assign something else to *p, but we can assign new value to p. const char **q = &p; declares a pointer to a pointer. We can’t assign something else to **q, but we can assign new values to q and *q. *q = “abcde”; changes p to point to “abcde” const char *s = ++p; assigns address of literal ”bcde” to s. Again *s can’t be assigned a new value, but s can be changed. The statement printf(“%cn”, *++s) changes s to “cde” and first character at s is printed.
Question 2
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables
Cross
Only 1, 2 and 3
Cross
Only 1, 2 and 4
Tick
All
Cross
Only 1, 3 and 4


Question 2-Explanation: 
When a function is declared as const, it cannot modify data members of its class. When we don't want to modify an argument and pass it as reference or pointer, we use const qualifier so that the argument is not accidentally modified in function. Class data members can be declared as both const and static for class wide constants. Reference variables can be const when they refer a const location.
Question 3
Predict the output of following program.
#include <iostream>
using namespace std;
class Point
{
    int x, y;
public:
 Point(int i = 0, int j =0)
   { x = i; y = j;  }
   int getX() const { return x; }
   int getY() {return y;}
};

int main()
{
    const Point t;
    cout << t.getX() << " ";
    cout << t.gety();
    return 0;
}
Cross
Garbage Values
Cross
0 0
Cross
Compiler Error in line cout << t.getX() << " ";
Tick
Compiler Error in line cout << t.gety();


Question 3-Explanation: 
There is compiler Error in line cout << t.gety(); A const object can only call const functions.
Question 4
#include <stdio.h>
int main()
{
   const int x;
   x = 10;
   printf("%d", x);
   return 0;
}
Tick
Compiler Error
Cross
10
Cross
0
Cross
Runtime Error


Question 4-Explanation: 
One cannot change the value of 'const' variable except at the time of initialization. Compiler does check this.
Question 5
Output of C++ program?
#include <iostream>
int const s=9;
int main()
{
    std::cout << s;
    return 0;
}
Contributed by Pravasi Meet
Tick
9
Cross
Compiler Error


Question 5-Explanation: 
The above program compiles & runs fine. Const keyword can be put after the variable name or before variable name. But most programmers prefer to put const keyword before the variable name.
There are 5 questions to complete.

  • Last Updated : 27 Sep, 2023

Similar Reads