April 29, 2020
On Wednesday, 29 April 2020 at 10:36:59 UTC, IGotD- wrote:
> I'm incompetent so I would just write:
>
> int test(int* x, int* y) {
>      *x = 0;
>      *y = 1;
>      return 0;
> }

Ok in this simple case it's obvius.
For a real world example look at the source for strcmp():
https://code.woboq.org/userspace/glibc/string/strcmp.c.html

The trick is to load the value in a variable. The compiler can't optimize multiple pointer reads from the same pointer because the content could already be changed by an other pointer. restrict solves that, but if you now what is happening and why you can solve that by hand.


April 29, 2020
On Wednesday, 29 April 2020 at 10:46:57 UTC, random wrote:
>
> Ok in this simple case it's obvius.
> For a real world example look at the source for strcmp():
> https://code.woboq.org/userspace/glibc/string/strcmp.c.html
>
> The trick is to load the value in a variable. The compiler can't optimize multiple pointer reads from the same pointer because the content could already be changed by an other pointer. restrict solves that, but if you now what is happening and why you can solve that by hand.

In the strcmp example, shouldn't the compiler be able to do the same optimizations as you would use restrict because both pointers are declared const and the content do not change?
April 29, 2020
On Wednesday, 29 April 2020 at 12:37:29 UTC, IGotD- wrote:
>
> In the strcmp example, shouldn't the compiler be able to do the same optimizations as you would use restrict because both pointers are declared const and the content do not change?

Good question. My strcmp example is actually really bad, because if you never write through any pointer it doesn't make a difference ;) The way it is written is still interesting.

I made a quick test case to evaluate the influence of const:

https://godbolt.org/z/qRwFa9
https://godbolt.org/z/iEj7LV
https://godbolt.org/z/EMqDDy

int test(int * x, int * y, <const?> int * <restrict?> z)
{
    *y = *z;
    *x = *z;
    return *z;
}

As you can see from the compiler output const doesn't improve the optimization.
I think the compiler can't optimize it because const doesn't give you real guarantees in C.
You could just call the function like this.

int a;
test(&a, &a, &a);

"One mans constant is an other mans variable."





April 29, 2020
On Wednesday, 29 April 2020 at 16:19:55 UTC, random wrote:

And of course the workaround if you don't want to use restrict:

int test(int * x, int * y, int * z)
{
    int tmp = *z;
    *y = tmp;
    *x = tmp;
    return tmp;
}

Produces the same as the restrict version.
https://godbolt.org/z/yJJcMK
April 29, 2020
On 4/29/2020 9:19 AM, random wrote:
> I think the compiler can't optimize it because const doesn't give you real guarantees in C.

You'd be right.
April 29, 2020
This is what the D n.g. is about - informative, collegial, and useful! Thanks, fellows!
1 2 3 4 5 6 7
Next ›   Last »