incrementing struct members

user1508893 picture user1508893 · Sep 30, 2012 · Viewed 14.6k times · Source

Say I have a struct defined as follows

struct my_struct
{
     int num;
};

....

Here I have a pointer to my_struct and I want to do an increment on num

void foo(struct my_struct* my_ptr)
{
     // increment num
     // method #1
     my_ptr->num++;

     // method #2
     ++(my_ptr->num);

     // method #3
     my_ptr->++num;

}

Do these 3 ways of incrementing num do the same thing? While we're at it, is it true that pre-increment is more efficient than post-increment?

Thanks!

Answer

Peter Alexander picture Peter Alexander · Sep 30, 2012

First two will have the same effect (when on a line on their own like that), but the third method isn't valid C code (you can't put the ++ there).

As for efficiency, there is no difference. The difference you may have heard people talking about is when, in C++, you increment a non-pointer data type, such as an iterator. In some cases, pre-increment can be faster there.

You can see the generated code using GCC Explorer.

void foo(struct my_struct* my_ptr)
{
    my_ptr->num++;
}

void bar(struct my_struct* my_ptr)
{
    ++(my_ptr->num);
}

Output:

foo(my_struct*):                      # @foo(my_struct*)
    incl    (%rdi)
    ret

bar(my_struct*):                      # @bar(my_struct*)
    incl    (%rdi)
    ret

As you can see, there's no difference whatsoever.

The only possible difference between the first two is when you use them in expressions:

my_ptr->num = 0;
int x = my_ptr->num++; // x = 0

my_ptr->num = 0;
int y = ++my_ptr->num; // y = 1