有没有办法给出一个“答案”;昵称;在C中使用长名称/路径而不赋值的变量

有没有办法给出一个“答案”;昵称;在C中使用长名称/路径而不赋值的变量,c,C,在我使用存储在结构内部“深层”的数据的情况下,我希望有一种方法使用一个较短的名称来引用它,以提高可读性。有没有一种方法可以在不给局部变量或指针赋值的情况下实现这一点(函数上不需要) 例如: int foo (struct1 *in_strct1, struct2 *in_strct2, struct3 *out_strct3) // an exaggerated example for a function that calculates one of the zeroes of // a qu

在我使用存储在结构内部“深层”的数据的情况下,我希望有一种方法使用一个较短的名称来引用它,以提高可读性。有没有一种方法可以在不给局部变量或指针赋值的情况下实现这一点(函数上不需要)

例如:

int foo (struct1 *in_strct1, struct2 *in_strct2, struct3 *out_strct3)
// an exaggerated example for a function that calculates one of the zeroes of
// a quadratic equation, where the inputs and the output are hidden very deep
// inside the structures. 
{
    /*unnecessary assignment that aren't needed functionally, but without *
     *them the code would be unreadable.                                  */
    double a = in_strct1->sublevel1.sublevel2.somearray[5].a;  
    double b = in_strct2->somearray[3].sublevel2.sublevel3.b;
    double c = in_strct2->someotherarray[6].inside.even_deeper_inside.almost_there.c;
    double *res = &out_strct3->a_very_long_corredor.behind_the_blue_door.under_the_table.inside_the_box.on_the_left.res;
    //actual logic
    *res = (-b+sqrt(pow(b,2)-4*a*c))/(2*a);
    return 0;
} 

您应该始终努力提高可读性,而您对
a
b
c
的定义有助于实现这一点

我不担心这样做会带来任何开销:一个好的编译器应该优化
a
b
c
。如果有任何疑问,请检查输出组件


编写
const double a
代替
double a
等将对编译器有更大的帮助。

正如尤金在评论中指出的那样,可以使用#define,尽管它确实存在范围风险。另一种方法是创建指向它的指针。指针实际上是指向该位置的别名


不幸的是,这确实需要一个任务。。。但如果没有赋值,我认为这是不可能的。

在某些情况下,使用指针这样做可能会使某些编译器无法优化它们,从而使性能比使用普通变量更差。然而,对于这个具体的例子,指针可能在我能想到的所有情况下都是可优化的

在您的例子中,我建议在函数体中使用local#defines,然后在函数结束之前再次取消它们的定义

类似于

int foo (struct1 *in_strct1, struct2 *in_strct2, struct3 *out_strct3)
{
#define a (in_strct1->sublevel1.sublevel2.somearray[5].a)
#define b (in_strct2->somearray[3].sublevel2.sublevel3.b)
#define c (in_strct2->someotherarray[6].inside.even_deeper_inside.almost_there.c)

#define res (out_strct3->a_very_long_corredor.behind_the_blue_door.under_the_table.inside_the_box.on_the_left.res)
    //actual logic
    res = (-b+sqrt(pow(b,2)-4*a*c))/(2*a);
    return 0;

#undef a
#undef b
#undef c
} 

一个
#定义
宏?或者实现getter/setter。
#define
不局限于局部范围,而且是有风险的,因为如果您忘记了
#undef
,它将继续影响代码的其余部分,是否有更好(更安全)的解决方案?您当前使用的局部变量可能是您能做的最好的。如果您不知何故担心不必要的赋值-不要担心,当您告诉编译器优化代码时,不会有性能损失。是的,它会的。但是如果你介绍一个好的会议。。例如,在宏前面加上函数名。如果所有数据在结构中处于同一级别,则通常会设置一个快捷指针:
struct which*sp=&in_strct2->somearray[3]。subvel2.subvel3;res=sp->a+sp->b+sp->c
。但这对你的情况没有帮助。虽然这是真的,但我不确定它是如何回答这个问题的。至少现在是这样了。@DavidHoelzer实际上,如果我们将“无赋值”定义为“编译程序中无赋值”,这是有帮助的。我建议强调添加一点
const
,由于这也将增加未来可能修改HMMM的一些健壮性,IMO在_strct1
中添加
const到
const struct1*,尤其是在其函数声明中,更有用,因为可以从编译器中推导出
const`in
const double a