在C中通过重新引用传递的强制转换函数参数 [英] Cast function argument passed by rereference in C

查看:77
本文介绍了在C中通过重新引用传递的强制转换函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能.它适用于 short :

I have the following function. It works with short:

void foo (short n, short * res)
{
  *res = n*2;
}

我想将结果存储在 double 变量中.例如:

I want to store the result in double variable. For example:

short in = 5;
double out = 0;
foo(in,&out);

但是以这种方式,结果是一些垃圾.有没有办法在这种情况下强制转换这些类型,或者唯一的解决方案是使用一些 short 类型的临时变量?

But in that way the result is some garbage. Is there a way to cast these types in such situation, or the only solution is to use some temp variable of type short?

推荐答案

如果您无法更改该功能,那么我将执行以下操作:

If you cannot change the function, then I would do something like this:

short in = 5;
short tmp;
double out;
foo(in,&tmp);
out = tmp;

如果您经常这样做,请考虑像@einpoklum在他的 answer 中那样编写包装器:

If you do this a lot, consider writing a wrapper as @einpoklum did in his answer like this:

void foo_wrapper(short n, double *out)
{
    short tmp;
    foo(n, &tmp);
    out = tmp;
}

我认为从理论上讲,铸造是可能的,但我建议不要这样做.错误地进行操作的风险很高,并且可能会遇到难以解决的错误,并且如果执行显式强制转换,则编译器将不会向您发出警告.我在此答案

I guess it could theoretically be possible with casting, but I would advice against it. The risks of doing it wrong is high, and you might get hard chased bugs, and if you do explicit casts, the compiler will not give you warnings. I wrote a rant about casting in this answer

在这种特殊情况下,请注意函数 foo 不了解结果类型.因此,您将需要一个临时变量.您可以通过使用 out 变量来摆脱这种情况,因为它是自己的临时变量,并进行了一些强制转换,但我强烈建议不要这样做!

In this particular case, note that the function foo have no idea of the resulting type. So you will need a temporary variable. You could get rid of that by using the out variable as it's own temporary variable with some casting but I strongly advice against it!

short in = 5;
double out;
foo(in, (short*)&out);
out = *(short*)&out; // Evil! Avoid code like this!
printf("%f\n", out);

这在我的机器上可以使用,但是确实违反了@chqrlie在评论中所写的别名规则.不要这样!

This works on my machine, but it does violate aliasing rules as @chqrlie wrote in comments. Do NOT do like this!

@chqrlie还写了另一种方法,没有多余的变量,也没有恶意的转换.它有效,但是哎呀!也不要这样做:

@chqrlie also wrote an alternative approach with no extra variable and no evil casting. It works, but UGH! Don't do like this either:

short in = 5; 
foo(in, &in); // No! Just don't!
out = in;     

当然,如果您需要原始值,它将无法正常工作,但这很明显.这里的主要缺陷是,这简直是很糟糕的.不要为了其他目的而重复使用变量,而只是为了摆脱临时变量.

Of course it will not work if you need the original value, but that's pretty obvious. The major flaw here is that it's just plain bad. Don't reuse variables for different purposes just to get rid of a temporary variable.

这篇关于在C中通过重新引用传递的强制转换函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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