c++11 - Understanding C++ Primer 5th ed solution posted by Moothy section 2.21 -
i'm newbie c++ , i'm working through exercises on chapter 2.
have question on exercise 2.21.
solution given moothy found on github
exercise 2.21
explain each of following definitions.
indicate whether illegal and, if so, why.
int = 0;
(a) double* dp = &i;
answer:
(a): illegal, cannot initialize variable of type 'double *' rvalue of type 'int *'
i don't understand last part of answer " .. rvalue of int *".
&i address of variable , never pointer mentioned here.
why mention pointer here? , why rvalue of pointer int?
int*
means variable can contain address of integer variable. address of integer variable when placed on right hand side of assignment left hand side shouldint*
otherwise give wrong results. that's told here.
where pointer? dp
pointer not integer pointer that's why error.
rvalue
- value appears in rhs of assignment operator. a=b (r-value)
do know why need different pointers? suppose have pointer variable pointing chunk of integers.
bbbbbbb (bytes) | pointer(p) bbbbbbb (bytes) | p+1 if pointing int bbbbbbb | p+1 if ointing char
now if p++, move. okay if pointing int move( sizeof(int)) 4 bytes , if character 1 byte. allowed wrong r-value assignment. problematic. have careful enoough code properly.
now hope understand whole picture.
note:look saying can not initialize double *
r-value of int*
. r-value of int *
? address of integer variable. assigning double pointer r-value of int*
not r-value of double*
address of double
.
from msdn
every c++ expression either lvalue or rvalue. lvalue refers object persists beyond single expression. can think of lvalue object has name. variables, including nonmodifiable (const) variables, lvalues. rvalue temporary value not persist beyond expression uses it. better understand difference between lvalues , rvalues, consider following example:
for further example/clarification check question
Comments
Post a Comment