Restrict Keyword and Pointers inside structs
Asked Answered
A

2

19

By using the restrict keyword like this:

int f(int* restrict a, int* restrict b);

I can instruct the compiler that arrays a and b do not overlap. Say I have a structure:

struct s{
(...)
int* ip;
};

and write a function that takes two struct s objects:

int f2(struct s a, struct s b);

How can I similarly instruct the compiler in this case that a.ip and b.ip do not overlap?

Abfarad answered 9/11, 2012 at 11:22 Comment(0)
M
17

You can also use restrict inside a structure.

struct s {
    /* ... */
    int * restrict ip;
};

int f2(struct s a, struct s b)
{
    /* ... */
}

Thus a compiler can assume that a.ip and b.ip are used to refer to disjoint object for the duration of each invocation of the f2 function.

Myel answered 9/11, 2012 at 11:27 Comment(0)
E
-2

Check this pointer example , You might get some help.

// xa and xb pointers cannot overlap ie. point to same memmpry location.
void function (restrict int *xa, restrict int *xb)
{
    int temp = *xa;
    *xa = *xb;
    xb = temp;
}

If two pointers are declared as restrict then these two pointers doesnot overlap.

EDITED

Check this link for more examples

Epilepsy answered 9/11, 2012 at 11:29 Comment(2)
I don't see how this answers the question - OP clearly knows how to do it with plain pointers, the code's in the question.Subjective
Perhaps it would be a good solution to write a function that works with the types of a.ip and b.ip rather than a and b. That depends on the nature of the struct, if a and b are incomplete types uses in a OO design, then that method wouldn't work.Twinflower

© 2022 - 2024 — McMap. All rights reserved.