A more elegant way to update an index in a circular list?

I have a list of questions that will be executed by the user, they can start with any question, but they have an order for them, so for this I just maintain the index in the array and increase it like this:

CurrentQuestion = (++CurrentQuestion < questions.Length) ? CurrentQuestion : 0; 

It is not necessarily obvious what is happening here, is there a more elegant way to do this?

+4
source share
3 answers

I have a strong aversion to using ++ for a variable, and then this variable is again in the same expression. I believe this line works fine in C #, but strings are like undefined in C / C ++, and therefore they raise the flag for me. I would prefer

 CurrentQuestion = (CurrentQuestion+1) % questions.Length; 

I think this is an idiomatic way to do clock arithmetic in type C languages.

+11
source

It is not necessarily obvious what is happening here, is there a more elegant way to do this?

Although this is not immediately obvious to some, I know for sure what it does.

However, what you might want to consider is that it is more important to write readable code than to be smart. The code must be saved and you are NOT smarter than the compiler.

Write the code this way, 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 point is that this code is now readable and still optimized. It does exactly what other code does, and we can swap parts later without re-reading the code.

Also pay attention to some semantics that I used here.

  • Always use braces, even if you don’t think you need them.
  • Make CurrentQuestion = CurrentQuestion + 1; instead of CurrentQuestion += 1; or CurrentQuestion++; or ++CurrentQuestion; , because the first is much more explicit in intention. Always write intentional code.
+3
source

No need for conditional statement

  CurrentQuestion = ++CurrentQuestion % questions.Length; 

but I think which one you prefer is a matter of style more than anything else.

0
source

All Articles