gpt4 book ai didi

c++ - C 与 C++ 函数问题

转载 作者:太空狗 更新时间:2023-10-29 19:44:11 26 4
gpt4 key购买 nike

我正在学习 C,在开始学习 C++ 作为我的第一门编译语言后,我决定“回归基础”并学习 C。

关于每种语言处理函数的方式,我有两个问题。

首先,为什么 C“不关心”函数定义的范围,而 C++ 关心?

例如,

int main()
{
donothing();
return 0;
}

void donothing() { }

以上不会在 C++ 编译器中编译,而会在 C 编译器中编译。为什么是这样? C++ 主要不是 C 的扩展,应该主要“向后兼容”吗?

其次,我找到的书 ( Link to pdf ) 似乎没有说明 main 函数的返回类型。我四处查看并找到了其他书籍和网站,这些书籍和网站通常也不指定 main 函数的返回类型。如果我尝试编译一个没有为 main 指定返回类型的程序,它可以在 C 编译器中正常编译(尽管有一些警告),但它不能在 C++ 编译器中编译。再一次,这是为什么?始终将返回类型指定为整数而不是将其遗漏是更好的风格吗?

感谢您的帮助,顺便提一句,如果有人能推荐一本我应该买的更好的书,那就太好了!

最佳答案

Firstly, why does C "not care" about the scope that functions are defined in, whereas C++ does?

实际上,C 确实关心。只是 C89 允许隐式声明函数并从用法中推断其返回类型为 int 及其参数。 C99 不再允许这样做。

因此在您的示例中,就好像您已将原型(prototype)声明为

int dosomething();

隐式返回类型也是如此:缺少的返回类型在 C89 中被推断为 int 而不是 C99。使用 gcc -std=c99 -pedantic-errors 编译您的代码会产生类似于以下内容的结果:

main.c: In function 'main':
main.c:2:5: error: implicit declaration of function 'donothing' [-Wimplicit-function-declaration]
main.c: At top level:
main.c:5:6: error: conflicting types for 'donothing'
main.c:2:5: note: previous implicit declaration of 'donothing' was her

作为记录,这是我使用的代码:

int main() {
donothing();
return 0;
}
void donothing() { }

关于c++ - C 与 C++ 函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12743445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com