Why strict aliasing is required in C ?

Consider below C program.





// A C program to demonstrate need of strict 
// aliasing
// Value of 'a' can be accessed/modified either
// through 'a' or through 'b'
int a = 5;
int* b = &a;
int func(double* b)
    a = 1;
    // The below statement modifies 'a'
    *b = 5.10;
    return (a);
int main()
    printf("%d", func((double*)&a));
    return 0;


Output :


If we call as “func()”it will return constant 1. But it is also possible to call the function as “func((double *)&a)” which was supposed to return 1 but returning something else. The code was made to return constant 1 only! That’s a big problem but STRICT ALIASING fixes it.

Solution :
Use restrict qualifier keyword. It means you promise the compiler that something is not aliased with the pointer restrict keyword. If you break your promise you will only suffer. Please refer restrict keyword in C for details.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.