我在这个循环中做错了什么?

时间:2016-02-21 14:56:49

标签: c

#include<stdio.h>
int main()
{
       for ( int i = printf("\nFor loop initialized ") , printf("Intialized value of i is %i", i) ;
            i >= printf("\nCondition checked") , printf("Current value of i is") ;
            printf("\nValue of i is decremented") , i-- )
       {
             printf(" %i", i);
       }

    printf("\nCondition false, Loop exited.");
       return 0;
}

以下是gcc -Wall -std=c11 -pedantic-errors

给出的错误
5:53: error: expected declaration specifiers or '...' before string constant
5:84: error: expected declaration specifiers or '...' before 'i'
5:88: warning: value computed is not used [-Wunused-value]

什么是...

据我说,输出应该是:

For loop initialized Intialized value of i is 21  
Condition checked Current value of i is 21  
Value of i is decremented  
Condition checked Current value of i is 20  
Value of i is decremented  
Condition checked Current value of i is 19  
Value of i is decremented  
Condition checked Current value of i is 18  
Value of i is decremented  
Condition checked  
Condition false, Loop exited.

3 个答案:

答案 0 :(得分:1)

好的,这是正在发生的事情:

  1. 您使用的C版本不允许for循环内的声明。

  2. C99确实允许这样的声明,但是在printf初始化之后,{C} i导致语法错误,因为它不是另一个声明。

  3. 循环无限的原因是因为比较后的逗号运算符,导致循环连续表达式的值是比较后的printf的结果,它总是非-Zero。

答案 1 :(得分:0)

for循环的第一部分只能保存声明,而对printf的调用不是声明。您可以从第二个声明中调用printf。此外,没有必要将整个事情放在一条线上。

  for(int i=printf("\nFor loop initialized "), 
          j=printf("Intialized value of i is %i", i);

      i>=printf("\nCondition checked") && printf("Current value of i is");

      printf("\nValue of i is decremented"), i--)

答案 2 :(得分:-1)

...在&#39; C&#39;中称为变量参数。语言。如果你想将多个参数传递给一个未定义的字符串,那么在我们使用变量参数列表的那个时候,该函数可能在任何时候都不参数。

例如:

void myFunc(...)

这里myFunc可以采用多个参数 您可以参考以下网址以便更好地理解。

http://www.tutorialspoint.com/cprogramming/c_variable_arguments.htm

希望这会以某种方式消除您的怀疑。