C++11 range-based for loops without loop variable

前端 未结 10 1180
轮回少年
轮回少年 2020-12-24 04:33

In C++ I need to iterate a certain number of times, but I don\'t need an iteration variable. For example:

for( int x=0; x<10; ++x ) {
    /* code goes her         


        
10条回答
  •  误落风尘
    2020-12-24 05:24

    There may be a way to do it but I very much doubt it would be more elegant. What you have in that first loop is already the correct way to do it, limiting the scope/lifetime of the loop variable.

    I would simply ignore the unused variable warning (it's only an indication from the compiler that something may be wrong, after all) or use the compiler facilities (if available) to simply turn off the warning at that point.

    This may be possible with some sort of #pragma depending on your environment, or some implementations allow you to do things like:

    for (int x = 0; x < 10; ++x) {
        (void)x;
    
        // Other code goes here, that does not reference "x".
    }
    

    I've seen that void trick used for unused parameters in function bodies.

提交回复
热议问题