谁能解释一下C语言中的变量声明

标签 c variables cs50

我是编程新手,我正在学习在线编程类(class) CS50。所以我有一个任务是用 C 语言编写一个程序,用户输入一些单词(无论单词之前或之后有多少空间),我们必须打印每个单词的第一个首字母。所以我做了这个程序:

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

  int main(void)
  {
  int n;
  int i;
  string name = get_string();
  if(name != NULL)
  {
      if (name[0] != ' ')
      {
          printf("%c", toupper(name[0]));
      }
      for(i = 0, n = strlen(name); i < n; i++)
      {
          if(name[i] ==' ' && isalpha(name[i+1]))
          {
              printf("%c", toupper(name[i+1]));
          }
      }printf("\n");
    }
  }

但只有在声明变量int n;之后才正确完成。整数我; 在此之前,我什至无法编译程序。为什么?首先我声明了int ifor 循环中,但程序甚至没有编译。不幸的是,我试图声明外部循环及其正确性。我不明白这一点。有人可以解释一下吗? :)

最佳答案

所有变量和函数必须在使用前声明。必须先声明变量 i,然后才能将其用作 for 循环中的索引。

在 1989/1990 标准和更早的 K&R 语言版本下,所有声明都必须位于 block 中的任何可执行语句之前:

void foo( void )
{
  /** 
   * The variable i is used to control a for loop later on in the function,
   * but it must be declared before any executable statements.
   */
  int i;

  /**
   * Some amount of code here
   */

  for( i = 0; i < some_value; i++ ) // K&R and C90 do not allow declarations within the loop control expression
  {
    /**
     * The variable j is used only within the body of the for loop.
     * Like i, it must be declared before any executable statements
     * within the loop body.
     */
    int j;

    /**
     * Some amount of code here 
     */
    j = some_result();

    /**
     * More code here
     */
    printf( "j = %d\n", j );
  }
}

根据 1999 年标准,声明可以与其他语句混合,并且它们可以作为 for 循环的初始表达式的一部分出现:

void foo( void )
{
  /**
   * Some amount of code here
   */
  for ( int i = 0; i < some_value; i++ ) // C99 and later allow variable declarations within loop control expression
  {
    /**
     * Some code here
     */
    int j = some_result(); // declare j when you need it
    /**
     * More code here
     */
    printf( "j = %d\n", j );
  }
}

上面两个片段之间的主要区别在于,在第一种情况下,i 在整个函数体内可见,而在第二个片段中,它仅在函数体内可见。 for 循环。如果您需要 ifor 循环后面的任何代码都可见,那么您需要在循环控制表达式之外声明它:

int i;
for ( i = 0; i < some_value; i++ )
{
  ...
}
...
do_something_with( i );

同样,i 必须先声明,然后才能在循环控制表达式中使用;只是在第二种情况下,该声明是循环控制表达式的一部分。

编辑

不知道你用的是什么开发环境或者编译器。您可能想看看是否可以指定要编译的语言版本(例如,在 gcc 中,您可以指定 -ansi -std=c90 表示 1989/1990 版本,-std=c99 表示 1999 版本)。

关于谁能解释一下C语言中的变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791081/

相关文章:

javascript - jQuery 动态按钮选择器

c - 如何在函数体内引用与局部变量同名的全局变量?

cs50积分循环问题分号

cs50x马里奥金字塔不画

c - 为什么我的二分查找在未找到元素时返回 "true"?

c - C 中的无符号整数下溢

用 ifort 和 icc 编译和链接 Fortran 和 C

c - 循环有自己的堆栈记录吗? (也就是为什么这段代码合法)

c - 为什么这会做任何事情?

c - * 根据其使用上下文是否有不同的含义?