简体   繁体   English

有关功能和指针的功课需要帮助

[英]Need help for homework about function and pointers

Asume that f() returns a reference to an integer ( int & f(); ), f()+=5; 假设f()返回对整数的引用( int & f(); ), f()+=5; and f()=f()+5; f()=f()+5; are different, explain how and give pesudo code for f() to illustrate this difference. 是不同的,解释如何并给f()的pesudo代码来说明这种差异。

If p is an int *p , what is the difference between, these two statement in C++: 如果p是int *p ,那么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. 在第一个中,您可以使用f()声明两个静态变量和一个指向其中一个的静态指针。

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 . 对于第二个问题,提示是*pp之间的差异。 For example, I wouldn't use the second one in the case where p itself could be NULL. 例如,在p本身可能为NULL的情况下,我不会使用第二个。

f()+=5 could be different from f() = f() +5 if f() returned a reference to a different integer at each call. 如果f()在每次调用时返回对不同整数的引用,则f()+=5可能与f() = f() +5不同。 This could only happen if f() read from some global variable which was different each time that it was called. 只有当f()从某个全局变量读取时才会发生这种情况,每次调用它时都会有所不同。

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 . if (p!=NULL && *p !=0)if (*p !=0 && *p !=NULL)之间的区别在于第一个检查p是否为null然后检查p是否为int0 The second one only checks whether the int that p points to is 0 (and performs this check twice). 第二个只检查p指向的int是否为0 (并执行此检查两次)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM