C 编译器没有注意到错误并自行更正代码

C compiler not noticing errors and correcting code itself

所以我是 C 的初学者,我一直在关注 Primer Plus 第六版。 当我 运行 我的程序时,我注意到一些非常奇怪的事情,编译器没有按预期工作,例如

int main(){
    one_three();
    getchar();
    return 0;
}

void one_three(void){
    printf("one\n");
    two();
    printf("three");
}

void two(void){
    printf("two\n");

}


这是我的代码,有很多错误,因为没有函数原型声明,不包括头文件,但有些输出是如何仅通过发出警告来产生的,我认为这不应该发生 注意我有意删除了函数原型声明并包含头文件

输出为:

review1.c: In function 'main':
review1.c:2:5: warning: implicit declaration of function 'one_three' [-Wimplicit-function-declaration]
    2 |     one_three();
      |     ^~~~~~~~~
review1.c:3:5: warning: implicit declaration of function 'getchar' [-Wimplicit-function-declaration]
    3 |     getchar();
      |     ^~~~~~~
review1.c:1:1: note: 'getchar' is defined in header '<stdio.h>'; did you forget to '#include <stdio.h>'?
  +++ |+#include <stdio.h>
    1 | int main(){
review1.c: At top level:
review1.c:7:6: warning: conflicting types for 'one_three'
    7 | void one_three(void){
      |      ^~~~~~~~~
review1.c:2:5: note: previous implicit declaration of 'one_three' was here
    2 |     one_three();
      |     ^~~~~~~~~
review1.c: In function 'one_three':
review1.c:8:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    8 |     printf("one\n");
      |     ^~~~~~
review1.c:8:5: warning: incompatible implicit declaration of built-in function 'printf'
review1.c:8:5: note: include '<stdio.h>' or provide a declaration of 'printf'
review1.c:9:5: warning: implicit declaration of function 'two' [-Wimplicit-function-declaration]
    9 |     two();
      |     ^~~
review1.c: At top level:
review1.c:13:6: warning: conflicting types for 'two'
   13 | void two(void){
      |      ^~~
review1.c:9:5: note: previous implicit declaration of 'two' was here
    9 |     two();
      |     ^~~
review1.c: In function 'two':
review1.c:14:5: warning: incompatible implicit declaration of built-in function 'printf'
   14 |     printf("two\n");
      |     ^~~~~~
review1.c:14:5: note: include '<stdio.h>' or provide a declaration of 'printf'
one 
two
three

最后三行 "one" 二三是输出 请帮忙,我正在使用这个编译器

我希望它在必须的时候输出错误,而不是自己添加东西,这样我就可以从我的错误中吸取教训 使用带有扩展名的 visual studio 代码:C/C++ by microsoft, Code runner

您需要在函数中声明您正在使用它们的函数之上的方法。如果您将函数重新排序为两个,则 one_three,然后是 main。它应该有效。

C 的早期准标准版本具有为对象提供默认类型的概念,如果它们未明确指定类型的话。函数,如果未声明,则隐式键入为:

int func();

因此,一个没有原型的函数被假定为 return int 并采用未指定数量的参数。因为在编写旧代码时考虑到了这一点,许多编译器都向后兼容并编译这样的旧代码,但在使用这些旧结构时会发出警告。

在你的特定情况下,你可以摆脱你定义的函数的隐式函数声明,因为函数有 void return 类型并且没有尝试使用return 这些函数的值。对于 getcharprintf 函数,它们的 return 类型是 int 因此它们可以使用隐式声明。