tobilocker tobilocker - 3 months ago 24
C++ Question

Is returning a functions value from a for-loop bad practice in C++?

My colleague just had a look at my code and said, that according to "some standard" returning a functions value out of a for loop is bad practice.

The function looks something like this:

bool CentralWidget::isBitFieldFree(const QString& define, int lsb, int msb)
QString defineWithoutIndex = getDefineWithoutIndex(define);
for (int i = lsb; i <= msb; i++)
if ((registerBitMap[defineWithoutIndex] >> i) & 1)
return false; //Returning here early...
registerBitMap[defineWithoutIndex] |= 1 << i;
return true;


  1. Is there a a standard that bans this?

  2. is this concidered bad practice?

  3. if so: why?


There is no such standard as this in the world of . However in a more specific environment (such as a company), specialized standards might apply.

With that said, it's not bad practice, in general.

a) a standard that bans this?


b) is this concidered bad practice?


c) question is already answered.

Other than that, it lies under the scope of personal preference, and here is mine - but this obviously not a part of a real answer:

You want to return true, after you have looped over your string, so how could you do it elegantly inside the loop? With an if statement saying that if it's the last iteration, return true, at the end of the loop?

I think this puts more lines of code in your file, without any reason, and damaging severely the readability.