我有一个问题列表,用户将通过它们进行迭代。他们可以从任何问题开始,但这些问题是有顺序的。为了实现这个功能,我只需维护一个数组索引,并像下面这样递增它:
CurrentQuestion = (++CurrentQuestion < questions.Length) ? CurrentQuestion : 0;
这里发生的事情可能并不明显,有没有更优雅的方式来完成这个任务?
我有一个问题列表,用户将通过它们进行迭代。他们可以从任何问题开始,但这些问题是有顺序的。为了实现这个功能,我只需维护一个数组索引,并像下面这样递增它:
CurrentQuestion = (++CurrentQuestion < questions.Length) ? CurrentQuestion : 0;
这里发生的事情可能并不明显,有没有更优雅的方式来完成这个任务?
我强烈反感在同一语句中对变量使用 ++
,然后再次使用该变量。我认为这行代码在C#中可以工作正常,但是在C/C++中,这样的代码是未定义的,因此它引起了我的警觉。我更喜欢
CurrentQuestion = (CurrentQuestion+1) % questions.Length;
我认为这是在类C语言中进行时钟算术的惯用方式。
这里正在发生的事情并不一定显而易见,有没有更优雅的方式来做这件事情呢?
虽然对于一些人来说可能不是很明显,但我知道那是在干什么。
然而,你需要考虑的是写易读的代码比聪明的代码更重要。代码需要被维护,而你并不比编译器更聪明。
像这样写代码,并且对其满意:
//ensure that the CurrentQuestion counter increments and loops back around after hitting "list max"
CurrentQuestion = CurrentQuestion + 1;
if (CurrentQuestion >= questions.Length) {
CurrentQuestion = 0;
} // meta-comment: use braces incase you have to add more later
CurrentQuestion = CurrentQuestion + 1;
而不是CurrentQuestion += 1;
、CurrentQuestion++;
或++CurrentQuestion;
,因为第一种更加明确表达了意图。始终编写有意义的代码。CurrentQuestion
等于 questions.Length
。 - default.kramerCurrentQuestion
是基于零的索引,则增量操作 (CurrentQuestion = CurrentQuestion + 1
) 应在循环检查之前执行。 - csdCurrentQuestion += 1;
并不是更加“清晰”,而是更加“可维护”。我发现自己混淆了重点。>.< - jcolebrand没有必要使用条件运算符
CurrentQuestion = ++CurrentQuestion % questions.Length;
但我猜你更喜欢哪一个,这只是风格问题,而不是其他什么。
CurrentQuestion
进行两次赋值:一次是来自增量(++CurrentQuestion
),另一次是来自等号。 - csd++
了? - H HCurrentQuestion+1
更快。我个人认为这种写法更易于阅读,而且由于很容易进行优化,因此速度可能不会变慢。 - Rune FS
++
,而Lou关于它是惯用方式的说法是正确的。 - H H++
是许多程序员警惕的信号。你需要准确理解何时应用++
,这使得代码行更难读懂,而且可能是错误的。我的答案没有这样的问题,所以我认为它在这方面更好。 - Lou Franco