I have a list of questions that the user will iterate through, they can start at any question, but they do have a order to them, so in order to do this I just maintain an index into the array and increment it like so:
CurrentQuestion = (++CurrentQuestion < questions.Length) ? CurrentQuestion : 0;
It isn't necessarily obvious what is happening here, is there a more elegant way to do this?
I have a strong aversion to using ++
on a variable and then that variable again in the same statement. I believe this line works fine in C#, but lines like this are undefined in C/C++, and so they raise a flag for me. I would prefer
CurrentQuestion = (CurrentQuestion+1) % questions.Length;
Which I think of as the idiomatic way of doing clock-arithmetic in C-like languages.
It isn't necessarily obvious what is happening here, is there a more elegant way to do this?
While it's not immediately obvious to some, I know exactly what that's doing.
However, what you may want to consider is that it's more important to write readable code than it is to be clever. Code has to be maintained, and you are NOT smarter than the compiler.
Write the code like thus, and be happy with it:
//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
The important bit is that this code is now readable, and it's still optimized. It does exactly what the other code does, and we can change parts later without a lot of re-reading of the code.
Also note some semantics I used here.
CurrentQuestion = CurrentQuestion + 1;
instead of either CurrentQuestion += 1;
or CurrentQuestion++;
or ++CurrentQuestion;
because the first is much more explicit on intent. Always write intentful code.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With