本文介绍了“垃圾”是否是未定义的行为?通过将函数指针转换为void函数然后调用它来返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 说,像这样: int SayHelloThenReturnTen(void){ puts( Hello world) ; 返回10; } 然后稍后: (((void(*)(void))SayHelloThenReturnTen)(); 这样安全吗?通过强制转换为void指针破坏返回值是否安全?这是安全的跨平台平台,还是 未定义的行为 ?解决方案 安全吗? 将函数指针强制转换为任何函数指针类型都是安全的。将结果强制转换回原始类型将产生一个等于原始指针的指针值。 但是,不是安全的通过与该函数所指向的函数不兼容的类型的函数指针进行 call 调用。标准的第6.3.2.3/8段对此进行了明确规定: 可以转换指向一种类型函数的指针指向另一个类型的函数的指针,然后再次返回;结果将比较等于原始指针。 如果使用转换后的指针来调用a函数,该函数的类型与引用的类型不兼容,则的行为是不确定的。 (添加了强调) 通过强制转换破坏返回值是否安全?指向空指针? 您的示例并未演示这一点。相反,它演示了如何使用返回类型 void 转换为函数指针类型。再次,强制转换可以,但调用不可以。 这是安全的跨平台平台,还是这种不确定的行为? p> 这是不安全的并且具有未定义的行为。而且,绝对没有任何好处。您可以根据需要简单地忽略该函数的返回值。如果您想让编译器警告这样做,则 考虑到编译器可能有一点,并且 如果要传达给编译器您确实确实想忽略返回值,则将那个转换为更清晰,更简单和安全的方法无效: (void)SayHelloThenReturnTen(); Say, something like this:int SayHelloThenReturnTen(void) { puts("Hello world"); return 10;}Then later:((void(*)(void))SayHelloThenReturnTen)();Is that safe? Is it safe to "trash" the return value by casting to a void pointer? Is this safe and cross platform, or is this undefined behavior? 解决方案 Is that safe?It is safe to cast a function pointer to any function pointer type. Casting the result back to the original type will yield a pointer value equal to the the original pointer.It is not safe, however, to call a function via a function pointer of a type incompatible with the function to which it points. This is set out pretty clearly in paragraph 6.3.2.3/8 of the standard: A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.(Emphasis added) Is it safe to "trash" the return value by casting to a void pointer?Your example does not demonstrate that. Rather, it demonstrates casting to a function pointer type with a void return type. Again, the cast is ok, but the call is not. Is this safe and cross platform, or is this undefined behavior?It is unsafe and has undefined behavior. Moreover, there is absolutely no benefit to be gained. You can simply ignore the function's return value if you wish. If you're trying to silence compiler warnings about doing that, then,consider that maybe the compiler has a point, andif you want to convey to the compiler that you really do want to ignore the return value, then it is clearer, simpler, and safe to cast that to void:(void) SayHelloThenReturnTen(); 这篇关于“垃圾”是否是未定义的行为?通过将函数指针转换为void函数然后调用它来返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-31 05:00