为什么在C99中不允许隐式声明gets()? [英] Why is implicit declaration of gets() not allowed in C99?

查看:402
本文介绍了为什么在C99中不允许隐式声明gets()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习C语言编程,我指的是这本书中的代码,它显示了一些带有 gets()的源代码,而我的IDLE也可以识别它。但是仍然在编译时,我的编译器不同意。

I am starting to learn programming in C language the book I am refering to code shows some source code with gets() and my IDLE recognises it as well. But still while compiling it, my compiler doesn't agree with it.

有人可以帮我吗?我在主要功能中使用 gets(),并使用clang作为编译器。

Can anyone help me out? I am using gets() in the main function and using clang as the compiler.

推荐答案

扩大我的评论:

首先,从不使用 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.

这篇关于为什么在C99中不允许隐式声明gets()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆