Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict Keyword and Pointers inside structs

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?

like image 486
user697683 Avatar asked Nov 09 '12 11:11

user697683


People also ask

Should I use pointers in structs?

Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.

What does __ restrict mean in C?

In the C programming language (after 99 standard), a new keyword is introduced known as restrict. restrict keyword is mainly used in pointer declarations as a type qualifier for pointers. It doesn't add any new functionality. It is only a way for programmer to inform about an optimization that compiler can make.

How do you use restrict keywords?

When the restrict keyword is used with a pointer p, then it tells the compiler, that ptr is only way to access the object pointed by this. So compiler will not add any additional checks. If the programmer uses restrict keyword then violate the above condition, it will generate some un-defined behavior.

Does C++ have restrict keyword?

The restrict keyword is a feature of the C99 standard that can be useful to C/C++ programmers. It can be attributed to pointers to guarantee that no other pointer overlaps the referenced memory location. Using the Intel C++ compiler does not only limit it to C99.


1 Answers

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.

like image 143
md5 Avatar answered Oct 09 '22 11:10

md5