Is there a way to give a nickname to a variable with a long name / path without assignment in C

If I use data that is stored in "deep" internal structures, I want to use a shorter name to refer to it for better readability. Is there a way to do this without assigning a local variable or pointer (which are not needed functionally).

Example:

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;
} 
+4
source share
3 answers

You should always strive for readability, and your definitions a, band chelp achieve this.

- : a, b c. , - .

const double a double a .. .

+3

, #define, . . , , .

, ... , , , .

+1

Using pointers for this may make it impossible in some situations for some compilers to optimize them, which makes performance worse than using ordinary variables. However, for this particular example, pointers are likely to be optimized in all cases that I can think of.

In your case, I recommend using local #defines inside the function body, and then #undef them again to the end of the function.

Sort of...

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
} 
0
source

Source: https://habr.com/ru/post/1626870/


All Articles