如何理解变量赋值背后的逻辑?

问题描述 投票:-6回答:3

我是初学者,我怎么能理解这个错误?

方法1

#include <stdio.h>
int main(void) {
int a=b=c=6;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
return 0;
}

它显示错误:

prog.c:5:7: error: ‘b’ undeclared (first use in this function)
int a=b=c=6;
       ^
prog.c:5:7: note: each undeclared identifier is reported only once for             
each function it appears in
prog.c:5:9: error: ‘c’ undeclared (first use in this function)
int a=b=c=6;
         ^

方法2:

#include <stdio.h>
int main(void) {
int a,b,c;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
return 0;
}

我的输出是

0
0
0

这是由于返回0?有人请加入示例以便更好地理解吗?

c
3个回答
0
投票

你的错误是在这一行:

int a=b=c=6;

C要求在使用变量之前声明变量,这里你尝试在声明之前使用b。例如,与上述不同,以下是合法的:

int a = 1, b = a;

因为对b的赋值使用了已经声明的变量。


2
投票
  1. 获取IDE
  2. 读一本书。谷歌。不研究现有解决方案,不要提问。我知道这很容易问,但研究可以帮助你,而不仅仅是得到答案。

现在回答你的问题。或许,https://www.cprogramming.com/tutorial/c/lesson1.html向下滚动,阅读变量。

变量声明为:

int a; 
int b;
int c;

变量也可以在一行中声明,

int a, b, c;

您可以在声明变量时为变量赋值。

int a = 1;
int b = 2;
int c = 3;

或者,您可以在一行中声明并分配它们的值:

int a = 1, b = 2, c = 3;

上面的“int”是一种数据类型。它告诉编译器你要声明什么类型的变量。 C中有各种数据类型:int,float,char,double等。这些是基本数据类型。还有派生的数据类型等等,等等。

如果你没有为变量赋值,而你只打印它,它将打印一个垃圾值(在你的情况下为0,它可以是任何东西)。尝试按照上面的方法在方法#2中分配值,您将看到差异。

返回0用于指定应用程序的退出代码。 0表示应用程序已成功退出。如果失败,则返回0以外的值,但无论如何。

祝好运。学习使用谷歌。


0
投票

我将向您展示一些分配值的示例。

例01

#include <stdio.h>

void main() {
    int a, b, c;
    a = b = c = 6;

    printf("%d\n", a);
    printf("%d\n", b);
    printf("%d\n", c);
}

例02

#include <stdio.h>

void main() {
    int a = 6, b = 6, c = 6;

    printf("%d\n", a);
    printf("%d\n", b);
    printf("%d\n", c);
}

下一个代码和你做的一样。你不能假设它们总是为0. C语言不会自动初始化它们,因此变量只是垃圾。

#include <stdio.h>

void main() {
    int a, b, c;

    printf("%d\n", a);
    printf("%d\n", b);
    printf("%d\n", c);
}
© www.soinside.com 2019 - 2024. All rights reserved.