Why strict aliasing is required in C?


Here we will see, why we should use the strict aliasing in C. Before discussing that part, let us see one code, and try to analyze the output.

Example

#include<stdio.h>
int temp = 5;
int* var = &temp;
int my_function(double* var) {
   temp = 1;
   *var = 5.10; //this will change the value of temp
   return (temp);
}
main() {
   printf("%d", my_function((double*)&temp));
}

Output

1717986918

If we call the function my_function, then it will return 1. We can also call this using my_function((double*)&temp). This is supposed to return 1, but here we can see that this is returning something else. This code was made to return constant 1 only. To fix this problem, we can use Strict Aliasing.

Use restrict qualifier keyword. It indicates that we are promising to the compiler that something is not aliased with the pointer restrict keyword. If we break our promise, there will be some problems.

Updated on: 30-Jul-2019

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements