Whether the given statements are legal or illegal?
Question:
Explain each of the following definitions. Indicate whether any are illegal and if so why?
int i =0;
(a)double*dp = &i;
(b)int * IP =i;
(c)int *p=&i;
2.Assuming p is a pointer to int,Explain the following code:
if(p) //………
if(*p) //…….
Summary:
In the first question, we have to explain whether the given statements are legal or illegal. Here the statement a and b are illegal and statement c is a valid statement. In the second question, both statements are valid statements.
Explanation:
Question 1:-
The first statement in the question is “double* dp = &i”.The value of i here is zero and also it is an integer data type. But in the question we have double-pointer dp, it can assign only the address of double data types but we are trying to assign the address of integer data type. So the given statement is illegal.
The second statement is “int *ip=i;”.The value of i here is zero and also it is an integer data type. But in the question, we have declared an integer pointer which is used to store the address of integer data type but not the integer value. Thus the given statement is illegal.
The third statement in the question is “int *p=&i;”.The value of i here is zero and also it is an integer data type. The integer pointer p is assigned to the address of an integer value. As an integer pointer can point to the address of the integer data type, thus the given statement is valid.
Question 2 :
In the last statement in question,1 int *p = &i, the pointer p will have the address of “i” and the pointer *p gives the value of i. The value of pointer p is the address of i which will be like 0x7ffe37a56ca4, not zero. It returns true in the if-loop and the control flows to the statements inside the loop. The value of pointer *p is the value of i which will be zero. It returns false in the if-loop and the statements inside the loop will be skipped.
The program below explains both the questions clearly whether the given statements are legal or illegal.
Source code:
#include<iostream> using namespace std; int main() { int i=0; cout<<"i="<<i<<endl; int*p=&i; cout<<"p="<<p<<endl; cout<<"*p="<<*p<<endl<<endl; if(p) {cout<<"one"<<endl;} if(*p) { cout<<"Two"<<endl;} bool b1=p; cout<<"b1="<<b1<<endl; bool b2=*p; cout<<"b2="<<b2<<endl; }
Output:
Also, read Square, Algebra, Numerical, Analogy, Area, the following structures must be evident in your program.