Search code examples
cloopssyntaxregister-allocation

Declaration of an iterator out of a cycle and registered iterators: How useful they are?


Why some people declare an cycle's iterator out of them? Like this:

int do_work(const int iqt) {
    register int i;

    for (i = 0; i < iqt; i++) {
    /* very busy work ;d */
    }

    return 0;
}

Is it a good practice?

And another questions: is it profitable to mark every iterator with register keyword?


Solution

  • There are two things here:

    1. "Declaring the variable inside the loop" feature was added in C99, any legacy code before that would be bound to declare the variables before the loop. For the legacy code, it was more of a requirement than a practice. However, post C99 era, can have it either way. Some people (including me) find it useful to declare variables closest to their usage.

    2. The register keyword is not a guarantee, it's a hint to the compiler. Compilers are free to ignore it. Quoting C11, chapter §6.7.1

      A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.