Deep Analysis of Const Qualifier in C

前端 未结 9 1011
离开以前
离开以前 2020-11-30 08:26

Where does a const variable gets stored exactly and how does it behaviour change? Say for example:

const int i=10; // stores where ?  
main()  
         


        
9条回答
  •  青春惊慌失措
    2020-11-30 08:51

    Modifying your code to print the value:

    #include 
    
    main()
    {
       const int j=20;
       int *p;
       p=&j;
       (*p)++;
        printf("%d\n", j);
       return 0 ;
    }
    

    The above code, when compiled with gcc 4.3.2 at -O1 optimisation or above, results in the output 20 rather than 21. This shows that it hasn't really "worked" - it just appeared to work.

    A const qualifier isn't a request to have the variable placed in a particular kind of memory - it's a promise from you to the compiler, that you won't modify that variable by any means. The compiler can rely on your promise to optimise the code that's produced - and if you break your promise, it won't necessarily break in an obvious way, it may just produce strange results.

提交回复
热议问题