Open In App

Why strict aliasing is required in C ?

Last Updated : 08 Jan, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Consider below C program.




// A C program to demonstrate need of strict 
// aliasing
#include<stdio.h>
  
// 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 :

1717986918

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads