I finally trace down a typo bug, which is something similar to the following code. But shouldn't the compiler detect this (by default options)?
我终于追查了一个错字错误,这与下面的代码类似。但是编译器不应该检测到这个(默认选项)?
#include <stdio.h>
int main()
{
int c = c;
return printf("%d\n", c);
}
$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
3 个解决方案
#1
7
I don't see why it wouldn't compile. Definition happens prior to initialization. Of course this initialization is pointless, however, there's no reason it wouldn't work from the compilers stand point.
我不明白为什么它不会编译。定义在初始化之前发生。当然这种初始化是没有意义的,但是,没有理由不能从编译器的角度来看它。
C does not have the same types of protections that more modern languages like C# have. The C# compiler would give an error that you're using an unassigned variable. C doesn't care. It will not protect you from yourself.
C没有与C#等现代语言相同的保护类型。 C#编译器会给出一个错误,即您正在使用未分配的变量。 C不关心。它不会保护你自己。
#2
4
It's perfectly legitimate to use a variable in its own initializer. Consider a linked list:
在自己的初始化程序中使用变量是完全合法的。考虑一个链表:
#include <stdio.h>
struct node { struct node *prev, *next; int value; };
int main() {
struct node l[] = {{0, l + 1, 42}, {l, l + 2, 5}, {l, 0, 99}};
for (struct node *n = l; n; n = n->next)
printf("%d\n", n->value);
return 0;
}
In general, diagnosing when a value is used uninitialised is a difficult problem; although some compilers can detect it in some cases it doesn't make sense to require it to happen.
通常,诊断何时使用未初始化的值是一个难题;虽然有些编译器在某些情况下可以检测到它,但要求它发生是没有意义的。
#3
-4
If
int c;
c = c;
will compile, I do not see why int c = c;
won't compile.
将编译,我不明白为什么int c = c;不会编译。
#1
7
I don't see why it wouldn't compile. Definition happens prior to initialization. Of course this initialization is pointless, however, there's no reason it wouldn't work from the compilers stand point.
我不明白为什么它不会编译。定义在初始化之前发生。当然这种初始化是没有意义的,但是,没有理由不能从编译器的角度来看它。
C does not have the same types of protections that more modern languages like C# have. The C# compiler would give an error that you're using an unassigned variable. C doesn't care. It will not protect you from yourself.
C没有与C#等现代语言相同的保护类型。 C#编译器会给出一个错误,即您正在使用未分配的变量。 C不关心。它不会保护你自己。
#2
4
It's perfectly legitimate to use a variable in its own initializer. Consider a linked list:
在自己的初始化程序中使用变量是完全合法的。考虑一个链表:
#include <stdio.h>
struct node { struct node *prev, *next; int value; };
int main() {
struct node l[] = {{0, l + 1, 42}, {l, l + 2, 5}, {l, 0, 99}};
for (struct node *n = l; n; n = n->next)
printf("%d\n", n->value);
return 0;
}
In general, diagnosing when a value is used uninitialised is a difficult problem; although some compilers can detect it in some cases it doesn't make sense to require it to happen.
通常,诊断何时使用未初始化的值是一个难题;虽然有些编译器在某些情况下可以检测到它,但要求它发生是没有意义的。
#3
-4
If
int c;
c = c;
will compile, I do not see why int c = c;
won't compile.
将编译,我不明白为什么int c = c;不会编译。