gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:09:06 25 4
gpt4 key购买 nike

我是编程新手,我正在学习在线编程类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com