#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
Here the 'Sum'=2
这里'Sum'= 2
Another program:-
另一项计划: -
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
here the output 'sum' = 3
WHY so?? What is the problem in the code??
这里的输出'sum'= 3为什么呢?代码中有什么问题?
2 个解决方案
#1
3
This is Undefined Behavior. Using uninitialized variables (n
in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n
to a specific value in both codes, you'll start getting consistent results.
这是未定义的行为。使用未初始化的变量(两个片段中的n)可能会产生意外结果,这意味着运行第一个代码两次可能会产生不同的输出。任何一个代码都没有“正确”的输出,但是如果你将n设置为两个代码中的特定值,你将开始获得一致的结果。
This is UB (Undefined Behavior):
这是UB(未定义的行为):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
这不是:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
#2
2
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0
, in some 1
, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
如果不为C中的局部变量赋值,则其值未定义。所以在某些情况下它会是0,在某些情况下,在某些情况下,在某些情况下,完全不同你无法知道它会是什么,你永远不应该依赖它。相反,初始化您的局部变量:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2
#1
3
This is Undefined Behavior. Using uninitialized variables (n
in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n
to a specific value in both codes, you'll start getting consistent results.
这是未定义的行为。使用未初始化的变量(两个片段中的n)可能会产生意外结果,这意味着运行第一个代码两次可能会产生不同的输出。任何一个代码都没有“正确”的输出,但是如果你将n设置为两个代码中的特定值,你将开始获得一致的结果。
This is UB (Undefined Behavior):
这是UB(未定义的行为):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
这不是:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
#2
2
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0
, in some 1
, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
如果不为C中的局部变量赋值,则其值未定义。所以在某些情况下它会是0,在某些情况下,在某些情况下,在某些情况下,完全不同你无法知道它会是什么,你永远不应该依赖它。相反,初始化您的局部变量:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2