Q1 const Write a program in a single cpp file that contains a function main(), n
ID: 3893636 • Letter: Q
Question
Q1 const
Write a program in a single cpp file that contains a function main(), name the file const.cpp. In the main function:
1) declare a const integer variable d and try to initialize it at the second line see what is the error. Comment this line in order to proceed to the rest steps without compilation error.
2) declare a const integer variable c and initialize it to 0;
3) declare a pointer ptr that points to c; print the dereferencing of ptr.
4) try to increase the content of deference of ptr, e.g. (*ptr)++, see what is the error and explain.
5) declare a constant integer array arr initialized to {10, 20,30,40,50}; let ptr point to arr and print *ptr and *(ptr+1).
6) declare a constant pointer cptr which points to constant integer arr.
7) try to let cptr point to constant c, see what is the error.
Explanation / Answer
#include <iostream>
using namespace std;
int main() {
//const int d;
//d=10;
//error: uninitialized const 'd' [-fpermissive] const int d;
const int c=0;
int *ptr= &c;
cout<< *ptr;
//Error: data type mismatch: ptr can point to integer variable where as c is const integer
(*ptr)++;
//error: increment of read-only location '* ptr' (*ptr)++;
/*Explaination: Content of ptr does not change it value as it is declared as constant */
const int arr[]={10,20,30,40,50};
ptr=arr;
cout<<*ptr;
cout<<*(ptr+1);
/*Error: data type mismatch: ptr can point to integer variable where as arr is const integer array
*/
const int *cptr=arr;
cptr= &c;
//Error constant pointer doesnt change its address
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.