在 C++ 中,是“返回".与“返回NULL"相同吗? [英] In C++, is "return;" the same thing as "return NULL;"?

查看:18
本文介绍了在 C++ 中,是“返回".与“返回NULL"相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是 return; 和 C++ 中的 return NULL; 一样吗?

my question is return; the same as return NULL; in C++?

我了解在 C++ 中,return NULL; 与指针上下文中的 return 0; 相同.显然,对于整数,情况并非如此,因为 NULL 不能加、减等.有些人鼓励使用 0 而不是 NULL 作为指针,因为它更便于可移植性.我很好奇这是否是另一个发生等价的例子.

I understand that in C++, return NULL; is the same as return 0; in the context of pointers. Obviously for integers, this is not the case as NULL cannot be added, subtracted, etc. And that it is encouraged by some to use 0 instead of NULL for pointers because it is more convenient for portability. I'm curious if this is another instance where an equivalence occurs.

我怀疑它们是等价的,因为 return; 是说 return 'nothing' 而 NULL 是 'nothing'.但是,如果有人可以确认或否认这一点(当然有解释),我将不胜感激!

I suspect that they are equivalent because return; is saying return 'nothing' and NULL is 'nothing.' However, if someone can either confirm or deny this (with explanation, of course), I would be very grateful!

推荐答案

return;和C++中的return NULL;一样吗?

没有.

return 用于从没有返回值的函数中中断"出来,即返回类型为 void.

return is used to "break" out from a function that has no return value, i.e. a return type of void.

return NULL返回值NULL,其所在函数的返回类型必须与NULL兼容.

return NULL returns the value NULL, and the return type of the function it's found in must be compatible with NULL.

我理解在C++中,return NULL;与指针上下文中的return 0;是一样的.

I understand that in C++, return NULL; is the same as return 0; in the context of pointers.

有点.NULL 可能不等同于 0,但它至少会转换成原来的样子.

Sort of. NULL may not be equivalent to 0, but it will at least convert to something that is.

显然,对于整数,情况并非如此,因为 NULL 不能加、减等.

Obviously for integers, this is not the case as NULL cannot be added, subtracted, etc.

您可以很好地对指针执行加法和减法.但是,NULL 无论如何都必须具有整数类型(C++03 中的 4.10/1 和 18.1/4),所以它没有实际意义.NULL 很可能是一个扩展为 00UL 的宏.

You can perform addition and subtraction to pointers just fine. However, NULL must have integral type (4.10/1 and 18.1/4 in C++03) anyway so it's moot. NULL may very well be a macro that expands to 0 or 0UL.

如果它实际上是您编写的 NULL,一些现代编译器至少会警告您.

Some modern compilers will at least warn you if it was actually NULL you wrote, though.

有些人鼓励使用 0 而不是 NULL 作为指针,因为它更便于移植.我很好奇这是否是另一个发生等价的例子.

And that it is encouraged by some to use 0 instead of NULL for pointers because it is more convenient for portability. I'm curious if this is another instance where an equivalence occurs.

没有.我不同意这个建议.虽然我可以看到它的来源,但由于 NULL 的确切定义因实现而异,使用 NULL 将使其 更容易替换为nullptr 当你切换到 C++11 时,如果没有其他东西是自记录的.

No. And I disagree with this advice. Though I can see where it's coming from, since NULL's exact definition varies across implementations, using NULL will make it much easier to replace with nullptr when you switch to C++11, and if nothing else is self-documenting.

这篇关于在 C++ 中,是“返回".与“返回NULL"相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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