-6

So, it seems like 'i' is pretty much the universal counter in C++. It seems like in every for loop, people re-initialize 'i'. I have to ask, why don't they just initialize 'i' globally? 'i' would still have to be re-defined in each loop, so I don't see why there would be any confusion.

It just seems like this:

#include <iostream>
int i=0;

int main()
{
    for (i=0;i<3;i++)
    {
        std::cout << i << "\n"; 
    }
    for (i=0;i<5;i++)
    {
        std::cout << "hello" << "\n";   
    }

    return 0;
}

is easier to read, and faster to write than:

#include <iostream>

int main()
{
    for (int i=0;i<3;i++)
    {
        std::cout << i << "\n"; 
    }
    for (int i=0;i<5;i++)
    {
        std::cout << "hello" << "\n";   
    }

    return 0;
}
  • How is "I have to ask, why don't they just initialize 'i' globally?" not a question? –  Oct 17 '16 at 08:33
  • 3
    Its a matter of opinion, not a problem, at least, you got a great name – Treycos Oct 17 '16 at 08:33
  • 3
    defined `i` outside the loop may cause incidental usage of `i`, which we don't want to. Initialize i in every loop show our intent that it's an index to go over that loop. – Danh Oct 17 '16 at 08:35
  • Just take a look at http://stackoverflow.com/questions/484635/are-global-variables-bad – Garf365 Oct 17 '16 at 08:36
  • 5
    Because people have learned from experience that 1) globals are bad, 2) declaring things as close to their use as possible is a good thing, and 3) reducing keystrokes isn't very important. With time, you will also learn that. – molbdnilo Oct 17 '16 at 08:38
  • 1
    Imagine a algorithm function that needs a loop counter calls another algorithm function that needs a loop counter, and both of them happen to use a global `i`... It is just plain wrong. –  Oct 17 '16 at 08:43

1 Answers1

10

Excellent idea!

Here's a program that prints "hellohello" five times:

int i;

void print_twice(const std::string& s)
{
    for (i = 0; i < 2; i++)
    {
        std::cout << s;
    }
    std::cout << std::endl;
}

int main()
{
    for (i = 0; i < 5; i++)
    {
        print_twice("hello");
    }
}

Or... does it? (Ominous organ music plays. The crows caw. Sirens in the distance.)

molbdnilo
  • 64,751
  • 3
  • 43
  • 82