2

In c language programming, should I favour:

typedef struct
{
    Point_t points[4];
} Quad_t;

Over:

typedef Point_t Quad_t[4];

In terms of performance? and best practice?

Note that Point_t is defined as follows:

typedef union
{
    struct
    {
        int x;
        int y;
    };
    int coords[2];
} Point_t;

I found the first approach more readable and easier to handle when quads are passed across functions, however, the second approach just seems more direct.

Also, I couldn't sense difference in performance using either but I'm assuming that's because only a small portion of my code is using this type. (but still, I'd like to learn this tip for the future)

Many thanks in advance.
Hasan.

has981
  • 425
  • 4
  • 18

3 Answers3

3

I completely agree with your argument about readability when passing across functions. In general, I think that making typedefs for plain arrays leads to confusing code and I recommend avoiding the practice.

E.g.

typedef int Value[4];

void PassByValue(Value x) // Does it really?
{
    x[0] = x[3];
}

int main(void)
{
    Value x = {1, 2, 3, 4};

    PassByValue(x); // oops - passes a _pointer_ by value
                    // values in x can be changed.
}

While its true that actually passing an array by value (not possible without wrapping it in a structure) might be more expensive than passing a pointer at least it is clear what is going on at both the call site and in the function definition. If performance is an issue then you can explicity take the address of a structure and pass a pointer to it and this has the advantage of being more explicit at both sites.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
0

The best depends on the programmer's interest and likeness, However an even important perspective is of coding standards, for most of the programmers the first approach is more readable and understandable.

However second approach is kind of more useful when your code is going to be used by someone else or you need to explain it to someone of non-C background. I would suggest having a look on C programming standards, or a book for generalized coding concepts (like Code Complete 2nd edition by Steve McConnell, which is the best book to read about coding), this link may help.

Community
  • 1
  • 1
Amit
  • 13,134
  • 17
  • 77
  • 148
0

You may run into problems like this if you try to declare a pointer to a const Quad_t. Generally it is not advised (for simplicity sake) to mix up arrays with typedef.

Community
  • 1
  • 1
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98