Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********************************************************************
- * This program is wrong, I know, I just want to share. That's it. *
- * I mean the way to cheat the compiler *
- ********************************************************************/
- /* optimize.c */
- #include <stdio.h>
- int main()
- {
- const int n = 1; /* n is declared as a non-volatile constant */
- int *p = (int *)&n; /* p is a pointer to the constant n */
- printf("old n: %d\n", n);
- *p = 2; /* the constant n should not be changed when optimized */
- printf("new n: %d\n", n);
- return 0;
- }
- /*****************************************************
- * Comments in the code are the comments by context. *
- * In fact, const is not constant. It is a keyword *
- * preventing unintentional modification. *
- *****************************************************/
- /**********
- * OUTPUT *
- **********/
- (I optimized with -O3.)
- % gcc -W -Wall -O3 -ansi -pedantic -s optimize.c
- % ./a.out
- old n: 1
- new n: 2
- %
- /* In the output, new n is still 2,
- * even if the compiler has already optimized.
- * Compiler optimization doesn't solve for this case.
- * And lastly, forget syntax highlighting for the output. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement