C:根据变量的值在for语句中使用不同的条件

C. *_*Pat 1 c for-loop if-statement conditional-statements

所以我想实现一个for语句,其'length'和条件取决于我给它的number-of-entries变量的值.循环主要是读取文件.

例如,如果条目数的命令行输入是正整数,我希望循环运行的条目数迭代或直到达到文件的末尾; 如果number-of-entries的输入是-1,我希望循环运行直到文件结束.

有没有办法在不编写两次for循环的情况下执行此操作,每一个都嵌套在if语句中; 有更简洁的方法吗?问因为for循环中的语句是相同的; 唯一的区别是for参数中的条件.

以下是我知道我能做的事情:

if ( number_of_entries > 0 ) {
    for ( i = 0; i < number_of_entries; i++ ){
        // set of for statements
        // check to see if end of file is reached
        // this case stops when i reaches number_of_entries or EOF
    }
}

else if ( number_of_entries < 0 ) {
    for ( i = 0; i > number_of_entries; i++ ){
        // identical set of for statements
        // check to see if end of file is reached
        // this case stops at EOF because i will never reach number_of_entries
    }
}
Run Code Online (Sandbox Code Playgroud)

只是想知道我是否可以这样做,同时只保留一组语句; 因为在任何一种情况下他们都是一样的.

编辑:让我在第二种情况下澄清i ++:它应该仍然是i ++; 第二个循环仅在到达文件末尾时结束.直到那时我会继续增加.number_of_entries唯一可接受的输入是-1或任何正整数(在程序中检查此项).

Jea*_*bre 8

如何使用短路这样i只有在number_of_entries积极的情况下进行测试:

for ( i = 0; number_of_entries < 0 || i < number_of_entries; i++ ){
        // set of for statements
        // check to see if end of file is reached
    }
Run Code Online (Sandbox Code Playgroud)

如果number_of_entries是否定的,for循环是一个无限循环(你必须break在检测到文件结尾时使用内部)

因此,如果number_of_entries是正数,那么这是一个额外的测试,但考虑到循环的内容(文件读取),性能不会受到太大影响.简洁与原始速度.

  • "编辑:让我在第二种情况下澄清i ++:它应该仍然是i ++;第二个循环只在到达文件末尾时结束".OP没有任何错误"for(i = 0; i> number_of_entries; i ++){"也是一个无限循环. (2认同)