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?

Johan Bezem
  • 2,582
  • 1
  • 20
  • 47
user697683
  • 1,423
  • 13
  • 24

2 Answers2

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.

md5
  • 23,373
  • 3
  • 44
  • 93
-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

md5
  • 23,373
  • 3
  • 44
  • 93
riti
  • 255
  • 2
  • 11
  • 1
    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. – Mat Nov 09 '12 at 11:43
  • 1
    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. – Lundin Nov 09 '12 at 12:41