Thread: restrict

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    201

    restrict

    to my understanding of restrict keyword the following code should print something different for the 2 cases, but it prints the same.
    Am I doing something wrong?

    Code:
    void f1(int *x, int *y, size_t n)
    {
        for (int i = 0; i < n; i++)
        {
            x[i] *= *y;
            printf("%d ", x[i]);
        }
        puts("");
    }
    
    void f2(int *restrict x, int *restrict y, size_t n)
    {
        for (int i = 0; i < n; i++)
        {
            x[i] *= *y;
            printf("%d ", x[i]);
        }
        puts("");
    }
    
    
    int main( int argc, char *argv[] )
    {
        int arr [10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int arr2[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
        srand(12);
    
        int index = (rand() % ARRSIZE(arr));
        int *p1 = arr + index;
        int *p2 = arr2 + index;
    
        printf("index=%d\n\n", index);
    
        f1(arr, p1, ARRSIZE(arr));
        f2(arr2, p2, ARRSIZE(arr2));
        
        return ( 0 ) ;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Laserve
    to my understanding of restrict keyword the following code should print something different for the 2 cases, but it prints the same.
    Am I doing something wrong?
    Perhaps only in thinking that it "should print something different". Undefined behavior often, unfortunately, mimics well-defined behavior.

    I would say this example is similar to modifying a string literal. One platform may happily modify the string; another may seg fault. It depends on the implementation, and apparently the implementation you are using (and the one I tested) doesn't bomb out in this case.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to restrict memory usage of a c++ program
    By gogoc in forum C++ Programming
    Replies: 12
    Last Post: 05-20-2008, 09:05 AM
  2. Restrict scanf() input?
    By difficult.name in forum C Programming
    Replies: 4
    Last Post: 09-20-2004, 12:27 PM
  3. restrict and function pointers
    By Laserve in forum C Programming
    Replies: 13
    Last Post: 06-27-2004, 01:42 AM
  4. restrict float(double) number
    By SuperNewbie in forum C Programming
    Replies: 3
    Last Post: 05-13-2004, 04:35 AM
  5. Restrict myself?
    By KrAzY CrAb in forum A Brief History of Cprogramming.com
    Replies: 19
    Last Post: 03-13-2003, 05:23 PM