-1

define is absolutely not a good solution .

#define loop(n) for(int i=0;i<n;i++)
int main()
{
    int i = 0;
    loop(10000) { i++; };
    cout << i << endl;//i==0 here,because of naming duplication.
    getchar();
    return 0;
}

Is there any solution other than just use a very complicate name to replace i ?

iouvxz
  • 89
  • 9
  • 27
  • 4
    Why would you want to have such macro at all? – πάντα ῥεῖ Nov 28 '15 at 11:23
  • @ πάντα ῥεῖ just curious about c++ grammar . – iouvxz Nov 28 '15 at 11:26
  • Well, you could write a function and pass `n` and `i` as parameters, the latter as reference. – πάντα ῥεῖ Nov 28 '15 at 11:28
  • related http://stackoverflow.com/questions/33111043/how-to-make-custom-keyword-statement/33111578#33111578 –  Nov 28 '15 at 11:46
  • I'm not sure what your example is trying to demonstrate. If you are looking for a way to allow the `i` in the body to not be an accidental reference to the loop variable, then I think you should try to make that clearer (possibly by saying it explicitly). (With the syntax you're using, however, the answer is "no". There is no way to exclude the loop's control variable from the scope of the body of the loop. If you allow making the body of the loop a macro parameter, it might be possible, but that's a lot uglier and so is the solution.) – rici Nov 29 '15 at 00:38

1 Answers1

5

If I understand you correctly, the (evil) way to do it with macros would be:

#define loop(n) for (int i=0; i < n; ++i)

int main()
{
    loop(10000)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

A less evil solution would be with lambda functions:

template<typename T>
void loop(int n, T func)
{
    for (int i=0; i < n; ++i)
        func(i);
}

int main()
{
    loop(10000, [] (int i)
        {
             std::cout << i << std::endl;
        });
    return 0;
}

But don't do that in real code, just write the plain for statement and everybody will understand you.

rodrigo
  • 94,151
  • 12
  • 143
  • 190