且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在C99中不允许隐式声明gets()?

更新时间:2022-12-15 11:01:28

扩大我的评论:

首先,从不使用 gets(),无论出于何种原因,甚至在玩具代码中也是如此。如果您在示例程序中看到它,请忽略该示例并继续。它在C99中已弃用,并在C2011中从标准库完全中删除,因为它是一个主要的安全漏洞。由该功能引起的胃灼热值得打破30多年的遗留代码。

First, never use gets(), for any reason, even in toy code. If you see it in an example program, ignore the example and move on. It was deprecated in C99 and removed from the standard library completely in C2011 because it was a major security hole. The heartburn caused by that one function was worth breaking 30-some-odd years of legacy code.

其次,在C89和更早版本下,如果编译器在看到声明或定义之前看到了函数 call ,它将假定函数已返回 int -IOW,该函数的隐式声明为 int 。如果稍后在同一翻译单元中具有函数 definition ,并且该函数返回了 int ,则可以:

Second, under C89 and earlier, if the compiler saw a function call before it saw a declaration or definition, it would assume the function returned int - IOW, the function had an implicit declaration of int. If you had a function definition later in the same translation unit, and the function returned an int, you were fine:

int foo( void )
{
  int x = bar(); // bar *implicitly* declared to return int
}

int bar( void ) // implicit declaration matches definition, we're good
{
  return some_integer_value;
}

但是,如果 bar 没有 not 返回 int ,您会收到错误消息,因为隐式 int 声明与非 int 定义不匹配。

However, if bar did not return an int, you'd get an error because the implicit int declaration did not match up with the non-int definition.

gets()返回 char * ,而不是 int ,因此隐式声明 get 都是错误的。

gets() returns char *, not int, so an implicit declaration of gets is incorrect regardless.

C99完全删除了隐式 int 声明-从那时起,必须声明 all 个函数或在调用它们之前定义。

C99 removed implicit int declarations entirely - since then, all functions must be declared or defined before they are called.

编辑

出现隐式声明错误的最可能原因是因为您的编译器是最新版本,因此在 stdio.h 中不再有 gets 的声明。

The most likely reason you're getting that implicit declaration error is that your compiler is recent enough that it no longer has a declaration for gets in stdio.h.