如果我使用存储在“深层”结构内部的数据,我想要一种方法来使用更短的名称来引用它以提高可读性。有没有一种方法可以在不分配给局部变量或指针(功能上不需要)的情况下做到这一点。
例子:
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
等将对编译器有更多帮助。
关于c - 有没有一种方法可以将 "nickname"赋予具有长名称/路径的变量,而无需在 C 中进行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133370/