Asume that f() returns a reference to an integer ( int & f();
), f()+=5;
and f()=f()+5;
are different, explain how and give pesudo code for f() to illustrate this difference.
If p is an int *p
, what is the difference between, these two statement in C++:
if (p!=NULL && *p !=0)....
if (*p !=0 && p !=NULL)....
In the first, you can have f()
declare two static variables and a static pointer to one of them.
Then return them alternately for each call, something like (pseudo-code since it's homework):
def f():
static var1 = 0;
static var2 = 42;
static pointer curr_var = reference of var1
if curr_var == reference of var1:
curr_var = reference of var2
else:
curr_var = reference of var1
return curr_var
or, even worse:
def f():
static var1 = array[1024];
static idx = -1;
idx = (idx + 1) % 100
return reference of var1[idx]
For your second question, the hint is the difference between *p
and p
. For example, I wouldn't use the second one in the case where p
itself could be NULL.
f()+=5
could be different from f()
= f()
+5 if f()
returned a reference to a different integer at each call. This could only happen if f()
read from some global variable which was different each time that it was called.
The difference between if (p!=NULL && *p !=0)
and if (*p !=0 && *p !=NULL)
is that the first one checks whether p
is null and then checks whether the int
that p
points to is 0
. The second one only checks whether the int
that p
points to is 0
(and performs this check twice).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.