Advertisement
ptkrisada

optimize.c

Dec 8th, 2019
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. /********************************************************************
  2.  * This program is wrong, I know, I just want to share. That's it.  *
  3.  * I mean the way to cheat the compiler                             *
  4.  ********************************************************************/
  5. /* optimize.c */
  6. #include <stdio.h>
  7.  
  8. int main()
  9. {
  10.     const int n = 1;    /* n is declared as a non-volatile constant */
  11.     int *p = (int *)&n; /* p is a pointer to the constant n */
  12.  
  13.     printf("old n: %d\n", n);
  14.     *p = 2;             /* the constant n should not be changed when optimized */
  15.     printf("new n: %d\n", n);
  16.  
  17.     return 0;
  18. }
  19. /*****************************************************
  20.  * Comments in the code are the comments by context. *
  21.  * In fact, const is not constant. It is a keyword   *
  22.  * preventing unintentional modification.            *
  23.  *****************************************************/
  24. /**********
  25.  * OUTPUT *
  26.  **********/
  27. (I optimized with -O3.)
  28. % gcc -W -Wall -O3 -ansi -pedantic -s optimize.c
  29. % ./a.out
  30. old n: 1
  31. new n: 2
  32. %
  33. /* In the output, new n is still 2,
  34.  * even if the compiler has already optimized.
  35.  * Compiler optimization doesn't solve for this case.
  36.  * And lastly, forget syntax highlighting for the output. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement