malloc要不要强制转换返回值

对于这个问题,很多人肯定想当然的说必须强制转换之类的云云……实则不然,今天看《C语言核心技术》的时候明确说到

可以将一个void指针值指定给另一个对象指针数据类型;反之也行,这都不需要进行显式数据类型转换。

然后在c语言邮件组常见问题里发现这个了,原文是http://c-faq.com/malloc/mallocnocast.html,内容如下:

Q: What's wrong with casting malloc's return value?

A: Suppose that you call malloc but forget to #include <stdlib.h>. The compiler is likely to assume that malloc is a function returning int, which is of course incorrect, and will lead to trouble. Now, if your call to malloc is of the form

char *p = malloc(10);

the compiler will notice that you're seemingly assigning an integer to a pointer, and will likely emit a warning of the form ``assignment of pointer from integer lacks a cast'' (see question 7.6), which will alert you to the problem. (The problem is of course that you forgot to #include <stdlib.h>, not that you forgot to use a cast.) If, on the other hand, your call to malloc includes a cast:

char *p = (char *)malloc(10);

the compiler is likely to assume that you know what you're doing, that you really do want to convert the int returned by malloc to a pointer, and the compiler therefore probably won't warn you. But of course malloc does not return an int, so trying to convert the int that it doesn't return to a pointer is likely to lead to a different kind of trouble, which will be harder to track down.

(Of course, compilers are increasingly likely--especially under C99--to emit warnings whenever functions are called without prototypes in scope, and such a warning would alert you to the lack of <stdlib.h> whether casts were used or not.)

总结一句话,C语言中的void返回值类型不需要进行强制类型转换。(C++好像要,不然会报错)

ps:对于C中不转换会不会出问题或者警告,我测试了,没问题,环境是MinGW

转载于:https://my.oschina.net/nibnat/blog/194085

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值