c++ - 理解写得不好的代码,第二年 CS 过去的论文

标签 c++ c algorithm coding-style

<分区>

题目是描述代码做什么,函数做什么。

以下代码是二年级 C 和 C++ 模块过去试卷的一部分。任务是描述以下代码的作用。我已经完全按照所提供的方式编写了代码,并添加了一些我自己的评论。

int g(int * y, unsigned size, int z) {
    int tmp = y[0];
    // what type is unsigned size? Int I presume. Why would you add an int to an array of ints?
    int * b = y + size; 
    y[0] = z;
    // I have the most difficulty understanding the following.
    while (1) if (*(--b)==z){y[0] = tmp; return b - y;};
    // are the following 3 lines ever even reached?
    y[0] = tmp;
    if (tmp == z) return 0;
    else return -1;
}

最佳答案

// what type is unsigned size?

这是一个名为sizeunsigned int。您可以像在普通指针算术中一样将它添加到一个指针 - 将此指针推进到数组的末尾。

while (1) if (*(--b)==z){y[0] = tmp; return b - y;};

好的,我们有

  • while(1) = while(true),或“永远循环”
  • *(--b) 预递减 b 并从数组的该索引读取值
  • 如果我们找到 z,将第一个元素替换为我们从中读取的值并返回 b-y - 我们所在的数组索引的指针算法

即我们正在向后扫描数组以找到 z 的最后一个实例并返回我们找到它的索引。我们总是会在数组中找到 z,因为我们将它作为第一个元素放在那里,即如果 z 不在数组中,那么我们返回 0。

// are the following 3 lines ever even reached?

不,我不这么认为。

关于c++ - 理解写得不好的代码,第二年 CS 过去的论文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10177331/

相关文章:

c++ - 是否可以有相互引用的 C++ 模板?

PHP脚本编译c++文件并使用输入文件运行可执行文件

c - DevCPP 的库窗口

c - 在递归调用自身的函数中省略 "return"语句

java - 使用二分查找查找数字数组中出现奇数次的数字

mysql - MySQL 中的深度优先搜索

c++ - 无法在 Linux 中使用 curl 编译 - undefined reference

c++ - 在并行计算机上启动应用程序时出现性能问题

c++ - 嵌套模板 : "expected primary-expression before ' )'"

algorithm - 在不使用浮点运算的情况下确定哪个整数最接近 n 的第 k 个根?