开发者社区> 问答> 正文

为什么在for循环的初始语句中不能声明多个变量?

当使用带有一个变量的a时,我们将其声明为0,因为i = 0,如下所示

但是,当我们使用两个变量,就像我添加n = strlen以使代码更有效时,则未声明i = 0,而是使用逗号并声明了n = strlen(s)。为什么我们不能使用'i = 0;' 就像之前的代码一样?

编辑:cs50.h是由哈佛制作的沙箱cs50的一部分。无论如何,我得到了答案,谢谢。

#include <stdio.h>
#include <string.h>

int main(void)
{
    string s = get_string("Input:  ");
    printf("Output: ");
    for (int i = 0; i < strlen(s); i++)
    {
        printf("%c\n", s[i]);
    }
}
#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    string s = get_string("Input: ");
    printf("Output:\n");
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        printf("%c\n", s[i]);
    }
}

展开
收起
几许相思几点泪 2019-12-29 20:32:06 2964 0
1 条回答
写回答
取消 提交回答
  • 不知道我是否理解这个问题(尽管我喜欢)。您的两个代码段都起作用,不是吗?请注意,我们不知道其中的内容cs50.h,但是我尝试对其进行编译,并且它可以正常工作(编译和运行)。

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
      char *s = "Hello world!";
      printf("Output:\n");
      for (int i = 0, n = strlen(s); i < n; i++) {
        printf("%c\n", s[i]);
      }
    }
    
    

    这里有两件事可能是相关的;-如何for工作以及-变量声明/初始化如何工作。

    您可以这样考虑for: for(AAA; BBB; CCC) DDD; 与

    { // Important!
      AAA;
      while(BBB) {
        {
          DDD;
        }
        CCC;
      }
    } // Important!
    
    

    该// Important!括号是重要的,因为对于引入了一个新的领域,即i与n将无法访问外/后for循环。

    另一件事是声明/初始化。所以

    int i = 0, n = strlen(s);
    
    

    是两个变量的初始化:i,n。我不确定100%正确的词汇和规则(您可以参考标准),但是想法是声明看起来像: TYPE VAR1, VAR2, ..., VARn 其中,VARx是声明的变量名,或者是“赋值”,在这种情况下,它是初始化。

    UPDATE / PART2: 通常我会这样做:

    const int len = strlen(s);
    // Good practice to declare const what every you know wont change
    for(int i = 0; i < len; i++) {
      // whatever
    }
    
    

    但是,如果可以使混乱的昏迷/分号保持一致,又因为分号是必须的,那么让我们尝试将所有内容都变成分号,我已经尝试过了:

    for ({int i = 0; int n = strlen(s); }; i < n; i++) {
      // what ever
    }
    
    

    这没有编译,但是也没有意义,因为如果它可以“工作”(在我看来我可以但实际上不能),i并且n将在小块中声明,则不会在其他任何地方都可以访问,即i < n无法访问。因此,要使它们可访问,我们可以尝试以下方法:

    int i, n;
    for ({i = 0; n = strlen(s); }; i < n; i++) {
      printf("%c\n", s[i]);
    }
    
    

    现在,如果上面的for- while等效性为100%是正确的,那么这应该已经奏效,但是由于显然不是AAA必须是单个语句(通常是声明),所以它不能是一个块,即{...}。确切的编译器错误:

    cc     hola.c   -o hola
    hola.c: In function ‘main’:
    hola.c:8:8: error: expected expression before ‘{’ token
        8 |   for ({
          |        ^
    make: *** [<builtin>: hola] Error 1
    
    

    但是正如您所见,它已经非常丑陋了……所以,是的,您需要使用,来分隔声明/初始化并使用a ;来终止它。

    2019-12-29 20:33:24
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载