Why strict aliasing is required in C?

CServer Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 22:30:26