how this is possible in c(const variable)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinayvaka
    New Member
    • Nov 2007
    • 13

    how this is possible in c(const variable)

    hi to all
    i have stuggled a lot with the below code. just see the code and explanation and please tell me ur input on this

    i have a code like this
    void main()
    {
    const int i=10;
    int *p=&i;
    *p++;
    Printf("%d",i);
    }

    value it will display is 10.


    so here my question is accoriding to dennis the variable wich declare as const will be stored in codesigment(i.e read only memonry), means we cannot change the contents of the codesigment right??

    here my question is then how come pointer(her pointer p wich is holding address of const variable i) here changing the value of "i" if it is stored in code segment.
    i have asked lot of people but i didnt get the reply.. please send me as much as explanation as u people can
    thanks in advance.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    When you do *p++ you fetch the value of what p points to and make p point to
    the next item (whatever its type). In other words: you're not trying to increment
    the value of const int i. Try to do (*p)++ and see what happens.

    kind regards,

    Jos

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      Originally posted by vinayvaka
      int *p=&i;
      Here compiler will object - to the left is int *, to the right is const int*, you cant assign it without const_cast.

      Comment

      • vinayvaka
        New Member
        • Nov 2007
        • 13

        #4
        Originally posted by newb16
        Here compiler will object - to the left is int *, to the right is const int*, you cant assign it without const_cast.
        i am taking about c not c++. in c i will allow

        Comment

        • Tassos Souris
          New Member
          • Aug 2008
          • 152

          #5
          Declaring a variable const means that you can not change its value by using the same identifier. You can, however, change the value if you know where it is, and this is done with pointers:
          Code:
          const int var = 20;
          int *p = NULL;
          
          var = 20; /* wrong!! you cannot use var to change the value */
          
          /* You can however cheat!! That is, go to where the value is and change it from there, without var knowing it ;) */
          p = &var;
          *p = 100;
          
          fprintf( stdout, "\nThe value of var is: %d\n", var ); /* this will print 100 and not 20 */
          
          /* The same will be printed if you do: */
          fprintf( stdout, "\nThe value of *p is: %d\n", *p );
          Now, about the problem you encounter. Well, it is not a problem.. it is that you do NOT use the code that does what you want to do.. *p++ does smt else from what you want.
          What you want is to increment by one the value that is stored in the space pointed to by p. You do this in this way:
          Code:
          ( *p )++;
          /* or... */
          *p += 1;
          Let's see what is the difference between ( *p )++ and what you wrote *p++:

          *p++:
          Let's look at the precedence here: ++ has higher precendence over * thus it is evaluated first. However, ++ when it is used after the variable and not before it increments it after the value has been fetched. So, for now, ++ does nothing.
          Next comes *. It dereferences the pointer p; that is it takes you to the space where p points.
          Now that the value has been fetched, ++ takes action and increments by one its operand. Its operand is p, so it increases p by one; that means that p now points beyond the var variable.
          As far as the value is concerned, it's just discarded.

          ( *p )++:
          Notice, that only one thing must be changed in order to have your work done. That is, ++ must not increment p but where it points; that is *p. So, you must put parentheses around *p so that ++ operates on *p and not p. Now you have what you want.
          Let's evaluate the expression now:
          () and ++ have the same precendence and are evaluated from left to right.
          So, ( *p ) is evaluated first. Then, ++ takes place and you have what you
          want.

          Hope i helped!

          Comment

          • vinayvaka
            New Member
            • Nov 2007
            • 13

            #6
            Originally posted by Tassos Souris
            Declaring a variable const means that you can not change its value by using the same identifier. You can, however, change the value if you know where it is, and this is done with pointers:
            Code:
            const int var = 20;
            int *p = NULL;
            
            var = 20; /* wrong!! you cannot use var to change the value */
            
            /* You can however cheat!! That is, go to where the value is and change it from there, without var knowing it ;) */
            p = &var;
            *p = 100;
            
            fprintf( stdout, "\nThe value of var is: %d\n", var ); /* this will print 100 and not 20 */
            
            /* The same will be printed if you do: */
            fprintf( stdout, "\nThe value of *p is: %d\n", *p );
            Now, about the problem you encounter. Well, it is not a problem.. it is that you do NOT use the code that does what you want to do.. *p++ does smt else from what you want.
            What you want is to increment by one the value that is stored in the space pointed to by p. You do this in this way:
            Code:
            ( *p )++;
            /* or... */
            *p += 1;
            Let's see what is the difference between ( *p )++ and what you wrote *p++:

            *p++:
            Let's look at the precedence here: ++ has higher precendence over * thus it is evaluated first. However, ++ when it is used after the variable and not before it increments it after the value has been fetched. So, for now, ++ does nothing.
            Next comes *. It dereferences the pointer p; that is it takes you to the space where p points.
            Now that the value has been fetched, ++ takes action and increments by one its operand. Its operand is p, so it increases p by one; that means that p now points beyond the var variable.
            As far as the value is concerned, it's just discarded.

            ( *p )++:
            Notice, that only one thing must be changed in order to have your work done. That is, ++ must not increment p but where it points; that is *p. So, you must put parentheses around *p so that ++ operates on *p and not p. Now you have what you want.
            Let's evaluate the expression now:
            () and ++ have the same precendence and are evaluated from left to right.
            So, ( *p ) is evaluated first. Then, ++ takes place and you have what you
            want.

            Hope i helped!
            yes.. that was my proble only.. but here we are changing the value saved in code sigment right?? how its possible??

            Comment

            • Tassos Souris
              New Member
              • Aug 2008
              • 152

              #7
              As i said, when you you write:
              Code:
              const int var = 10;
              You cannot change the value that is stored in the space reserved fot var by the means of th e var identifier itself!!
              The const qualifier does not make the space immutable. What it does is that you cannot use the identifier that is bound with the value to change it. However, if you get to the space by other means, then you can of course change what it is stored there.

              Let me know if you understood it! I am glad to help!

              Comment

              • vinayvaka
                New Member
                • Nov 2007
                • 13

                #8
                Originally posted by Tassos Souris
                As i said, when you you write:
                Code:
                const int var = 10;
                You cannot change the value that is stored in the space reserved fot var by the means of th e var identifier itself!!
                The const qualifier does not make the space immutable. What it does is that you cannot use the identifier that is bound with the value to change it. However, if you get to the space by other means, then you can of course change what it is stored there.

                Let me know if you understood it! I am glad to help!


                fine tassos
                const int var =10;
                int *p=&var;
                *p=15;
                if i print the value of var i will give 15 right??
                here what my question is we are changing the value saved in "code sigment" that is readonly memory "var" how its possible..
                hope i understood what i'm tell right??
                please let me know if not??

                Comment

                • Tassos Souris
                  New Member
                  • Aug 2008
                  • 152

                  #9
                  Well, for start code segment is another thing... http://en.wikipedia.or g/wiki/Code_segment

                  Forget about code segments...

                  Let's focus on the const qualifier now...

                  Question: What does the const qualifier?

                  Answer: Nothing!!!!!!!
                  What it does is to give you an ILLUSION that the variable will not be changed...
                  The Standard quarantees nothing about the const qualifier.. It just says that a strict conforming program may not modify an object that is defined with const.
                  The sure thing is that you can not modify an object defined with const by using its name..So, if const int var =10; then you cannot do var = 100;
                  Then, whether you can change the space reserved for var with other means (pointers) is implementation defined. An implementation MAY chooce to put obje cts with the const qualifier in read-only memory, thus trying to modify the space in all means (and by pointers!!!) will trigger a runtime error.
                  If a compiler chooces to put const objects as the other ones, then you can modify the space reserved for var using pointers. Specifically, the Standard says:
                  An object that is defined with `const' may not be modified
                  in any way by a strictly conforming program (so since `var'
                  above is const, it may not be modified; if it *is* modified,
                  the behavior is undefined).

                  So, in practice you cannot be sure what happens with const.
                  To use it in a Standard and portable way, when you define a object to be const then let it be const!!!
                  This is the case most times; i am sure you did this example by reading a book or smt like that... when you write a program and you chooce to make an object const then you chooce to make it immutable... so why change it? why use pointers to access the space and modify it? Can you understand what i am saying?

                  Hope i helped!

                  Comment

                  • vinayvaka
                    New Member
                    • Nov 2007
                    • 13

                    #10
                    yes thanks a lot............ ............... ..........

                    Comment

                    • Tassos Souris
                      New Member
                      • Aug 2008
                      • 152

                      #11
                      As a last guideline, let me tell you my view on const:

                      I use it just as a naming convention so that i can remember that the object must not change. As i use a variable all in capital letters in python as a naming convention to mimic #defines, i use const so that i can remember that the object must not be changed.
                      Well, that's my view.. Some may agree and some may not...
                      The thing is that const is not well described in the Standard and you must be careful when using it.

                      Comment

                      • Banfa
                        Recognized Expert Expert
                        • Feb 2006
                        • 9067

                        #12
                        Originally posted by Tassos Souris
                        Declaring a variable const means that you can not change its value by using the same identifier. You can, however, change the value if you know where it is, and this is done with pointers:
                        This is only true in some cases, many platforms (but not PCs generally) will put const variables into const physical data (flash normally). In this case even if you create a non-const pointer to the variable you still can not change its value because it is in memory that you physically can not write to.

                        It is extremely poor form to use a hack like this to change a const variable even on a platform that allows it and is likely to cause confusion and maintenance issues.

                        If the variable is const then don't change its value. If you need to change its value then it is not a const variable.

                        Comment

                        • Tassos Souris
                          New Member
                          • Aug 2008
                          • 152

                          #13
                          Originally posted by Banfa
                          This is only true in some cases, many platforms (but not PCs generally) will put const variables into const physical data (flash normally). In this case even if you create a non-const pointer to the variable you still can not change its value because it is in memory that you physically can not write to.

                          It is extremely poor form to use a hack like this to change a const variable even on a platform that allows it and is likely to cause confusion and maintenance issues.

                          If the variable is const then don't change its value. If you need to change its value then it is not a const variable.
                          Yes i agree.... read my post #9...

                          Comment

                          • Banfa
                            Recognized Expert Expert
                            • Feb 2006
                            • 9067

                            #14
                            Originally posted by Tassos Souris
                            Yes i agree.... read my post #9...
                            Ah, so that would be the one post in the thread I didn't bother reading fully before replying then. Opps, sorry :-)

                            Comment

                            • weaknessforcats
                              Recognized Expert Expert
                              • Mar 2007
                              • 9214

                              #15
                              Originally posted by Tassos Souris
                              You cannot change the value that is stored in the space reserved fot var by the means of th e var identifier itself!!
                              The const qualifier does not make the space immutable. What it does is that you cannot use the identifier that is bound with the value to change it. However, if you get to the space by other means, then you can of course change what it is stored there.
                              The const qualifer does make the space immutable. You are correct that you cannot use the const identifier to change the value of the const. You are incorrect that you can change it by other means. If you try that the results are indeterminate.

                              Consider this code:
                              Code:
                              const int var = 10;
                              int* ptr = (int*)&var;
                              *ptr = 20;
                              cout << var << " " << *ptr << endl;
                              cout << &var << " " << ptr << endl;
                              Running this code on Visual Studio.NET 2008 I get:

                              10 20
                              0012FF40 0012FF40

                              It appears the 10 and the 20 are at the same location in memory.

                              That means the part of my program that uses var sees 10 and the part that uses *ptr sees 20. This is classic indeterminate results. Other compilers may behave differently.

                              There are safe ways to cast off a const but this isn't it.

                              Comment

                              Working...