我希望有人能解释 的条件语句是如何返回 (i % 2) 的? &odd : &even;
能够判断 i
是偶数还是奇数。
我很困惑,因为 &odd
和 &even
是对 int odd[]
和 int even[]
的引用.据我了解,条件语句不会“遍历”数组并检查数组中的所有值以检查 (i % 2)
的条件是否匹配。下面是代码。我希望我已经足够清楚了。
#include <iostream>
int odd[] = { 1, 3, 5, 7, 9 };
int even[] = { 0, 2, 4, 6, 8 };
decltype(odd)* arrptr(int i) { // equivalent to int (*arrPtr(int))[5] or
// auto arrPtr(int i) -> int(*)[5]
return (i % 2) ? &odd : &even;
}
int main()
{
arrptr(3);
system("pause");
return 0;
}
最佳答案
这是为了解释我在您发布到其他答案的评论中看到的困惑。
How does the conditional statement know the difference between what is a even number or an odd number?
事实并非如此。它只是计算第一个表达式并检查真值。与 if
一样,您插入逻辑来决定 i
是偶数还是奇数。通常这是使用整数提醒运算符 i % 2
完成的。
The expressions in the conditional statement are nothing more than references to an array named &odd[] and &even[]. There is nothing in the program that tells the program what even or odd number means.
不,第二个和第三个参数是&odd[]
和&even[]
。你错过了第一个;它是一个条件表达式,将被评估为真值。
i % 2
将返回 0
如果 i
是偶数,否则返回 1
如果 i
很奇怪。该整数值将隐式转换为 bool 值,因为表达式是在 bool 上下文中计算的。在 C 和 C++ 中,任何非零值都是 true 否则 false。因此,如果 i
是偶数,它将返回 false,否则返回 true。
我认为让您感到困惑的是操作数 2 和 3 的名称;在心里将它们重命名为 evenArray
和 oddArray
。运算符所做的是,它返回一个数组。哪个数组?它根据第一个操作数决定,而第一个操作数又根据参数 i
的奇偶校验(偶数/奇数)决定它。
关于c++ - 条件运算符和数组/返回指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28016645/