When to use const modifier?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leonardo Korndorfer

    When to use const modifier?

    Hi,

    I'm litle confused by the const modifier, particularly when use const
    char* or char*.
    Some dude over here said it should be const char when you dont modify
    it content inside the function, I read somewhere that it when you
    won't modify after its initialization. ..

    So when exactly do I use one or another? Is it *wrong* not use const
    when I should?

    thanks in advance.
    Leonardo.
  • Ian Collins

    #2
    Re: When to use const modifier?

    Leonardo Korndorfer wrote:
    Hi,
    >
    I'm litle confused by the const modifier, particularly when use const
    char* or char*.
    Some dude over here said it should be const char when you dont modify
    it content inside the function, I read somewhere that it when you
    won't modify after its initialization. ..
    >
    Both.
    So when exactly do I use one or another? Is it *wrong* not use const
    when I should?
    >
    Not using const is only a problem when the object is a real constant,
    like a string literal.

    I other cases, const expresses an intent.

    --
    Ian Collins.

    Comment

    • santosh

      #3
      Re: When to use const modifier?

      Leonardo Korndorfer wrote:
      Hi,
      >
      I'm litle confused by the const modifier, particularly when use const
      char* or char*.
      Some dude over here said it should be const char when you dont modify
      it content inside the function,
      Const qualifying a function parameter will help the compiler diagnose
      any attempt to modify the concerned object within the function.
      I read somewhere that it when you
      won't modify after its initialization. ..
      The behaviour is the same here.
      So when exactly do I use one or another?
      That depends on how the object will be used. If the object will only be
      initialised and not modified thereafter then you can const qualify it's
      declaration. If OTOH you want only certain functions to not modify an
      array object, you can const qualify the relevant parameter. This way
      other functions can still modify the array. An alternative is to wrap
      the array inside a structure before passing it to the function. But
      this will not help you catch inadvertent modifications, which is the
      main use of const.
      Is it *wrong* not use const
      when I should?
      No. But it's helpful to take advantage of language features to make your
      job easier.

      Comment

      • santosh

        #4
        Re: When to use const modifier?

        Ian Collins wrote:
        Leonardo Korndorfer wrote:
        >Hi,
        >>
        >I'm litle confused by the const modifier, particularly when use const
        >char* or char*.
        >Some dude over here said it should be const char when you dont modify
        >it content inside the function, I read somewhere that it when you
        >won't modify after its initialization. ..
        >>
        Both.
        >
        >So when exactly do I use one or another? Is it *wrong* not use const
        >when I should?
        >>
        Not using const is only a problem when the object is a real constant,
        like a string literal.
        Are string literals "real constants", whatever that means? I thought you
        were just supposed to pretend that they were constants, and treat them
        as such, to prevent the wrath of UB.

        Comment

        • Andrew Kerr

          #5
          Re: When to use const modifier?

          santosh wrote:
          Ian Collins wrote:
          >Leonardo Korndorfer wrote:
          >>I'm litle confused by the const modifier, particularly when use const
          >
          Are string literals "real constants", whatever that means? I thought you
          were just supposed to pretend that they were constants, and treat them
          as such, to prevent the wrath of UB.
          >
          Here, C's subtle goals for portability surface. Some memory pages are
          marked read-only. Any attempted write to a read-only page by a user mode
          program [contrasted with supervisor mode running the OS's kernel] will
          result in an interrupt raised by the Memory Management Unit [MMU], the
          part of the CPU that translates virtual addresses to physical addresses.
          This interrupt notifies the kernel your program is behaving badly. The
          default behavior in this case is an abrupt termination known as a "core
          dump."

          Executable files produced by modern linkers are partitioned into
          segments. The ".data" segment is expected to be read-only and *may* be
          mapped to a read-only page in virtual memory. Attempting to write it
          results in the above behavior. This is the meaning of "real constant":
          the hardware and OS will not permit you to write it after the loader
          brings that segment into memory and protects the page. String literals
          are typically placed in the ".data" segment, so treat them as "real
          constants."

          This differs somewhat from use of the 'const' keyword. When const is
          used in a variable definition, the compiler typically attempts to infer
          its value. If the compiler can guess the initial value at compile time,
          and by definition the variable's value cannot change after
          initialization, then it may optimize the value away. That is, replace
          all instructions loading that variable with load-immediate instructions.
          If you attempt to take the address of that variable, or the compiler
          chooses not to get rid of it, it may place that value in the ".data"
          segment again resulting in a "real constant."

          You may implicitly cast a non-const to const. Depending on how you
          structure your program, you may know that, by design, some function
          should not have reason to modify its data. You may declare that data
          const to express this fact. Because the compiler knows that nothing will
          attempt to modify the data when the particular function is called, all
          sorts of optimization trickery becomes possible. The function may be
          executed concurrently with others, an OpenMP compiler may spawn separate
          threads, VLIW compilers may issue multiple instructions with correct
          knowledge that no data dependencies exist, and so on.

          Given a constant variable, you may cast away the const property and then
          write to it. This is only guaranteed to work if you are certain that the
          variable was defined as nonconst. The following example illustrates the
          difference between "real constant" and "not as constant as it seems."

          void modify(const int *p_a) {
          *((int *)p_a) = 7; // take life into own hands; hope caller
          // knew what s/he was doing
          }

          int main() {
          int a = 5;
          const int b = 5;

          modify(&a); // ok: passing the address of a non-const int

          modify(&b); // bad: passing the address of a const int.
          // Results undefined.

          return 0;
          }

          The first call to modify() works because modify()'s body correctly
          assumes that it has really received a pointer to a non-const int. The
          second call is likely to fail because that assumption is incorrect.

          The author of the modify() function is making some pretty bold
          assumptions about the caller and is lying about it in its parameter
          list. That's not advised.

          Hope this clarifies things.

          --
          Andrew Kerr

          Comment

          • Walter Roberson

            #6
            Re: When to use const modifier?

            In article <484461DE.80306 03@gatech.edu>,
            Andrew Kerr <arkerr@gatech. eduwrote:
            >Here, C's subtle goals for portability surface. Some memory pages are
            >marked read-only. Any attempted write to a read-only page by a user mode
            >program [contrasted with supervisor mode running the OS's kernel] will
            >result in an interrupt raised by the Memory Management Unit [MMU], the
            >part of the CPU that translates virtual addresses to physical addresses.
            >This interrupt notifies the kernel your program is behaving badly.
            These things are -commonly- true, but none of them are -necessarily-
            true: it is valid for C to run on systems that function quite differently.
            >The
            >default behavior in this case is an abrupt termination known as a "core
            >dump."
            Is that a new behaviour in C99? I can't find any reference to it
            in C89, not even in the Rationale.

            >Executable files produced by modern linkers are partitioned into
            >segments. The ".data" segment is expected to be read-only and *may* be
            >mapped to a read-only page in virtual memory.
            And for the systems that do not use "segments", or which do
            not have a ".data" segment? Do you simply define those away as
            not having "modern linkers" ?
            --
            "Eightly percent of the people in the world are fools and the
            rest of us are in danger of contamination." -- Walter Matthau

            Comment

            • Malcolm McLean

              #7
              Re: When to use const modifier?


              "Leonardo Korndorfer" <leokorndorfer@ gmail.comwrote in message
              Hi,
              >
              I'm litle confused by the const modifier, particularly when use const
              char* or char*.
              Some dude over here said it should be const char when you dont modify
              it content inside the function, I read somewhere that it when you
              won't modify after its initialization. ..
              >
              So when exactly do I use one or another? Is it *wrong* not use const
              when I should?
              >
              Use const when you don't modify the string (or other thing pointed to)
              within the function. constness only applies within the function's scope.
              Outside the variables can be modified, and in fact usually are modified.
              Only rarely is data provided in read-only arrays typed into the program
              directly.

              There's a bit of debate about the virtues of const. One problem is const
              poisoning. Once a pointer becomes const, everything it touches has to be
              const. Another problem is that constness applies only to the object directly
              pointed to. However frequently structures contain other pointers, and you
              want to const them as well.
              So it is not exactly wrong to avoid const. Personally I try to keep it to a
              minimum. However if I am writing code to publish on my website const will
              usually be included for a constant pointer parameter that the user provides.
              If the pointer parameter is returned by another function in the same file,
              however, I usually won't declare it const.

              --
              Free games and programming goodies.



              --
              Free games and programming goodies.



              Comment

              • Eric Sosman

                #8
                Re: When to use const modifier?

                Malcolm McLean wrote:
                >
                "Leonardo Korndorfer" <leokorndorfer@ gmail.comwrote in message
                >Hi,
                >>
                >I'm litle confused by the const modifier, particularly when use const
                >char* or char*.
                >Some dude over here said it should be const char when you dont modify
                >it content inside the function, I read somewhere that it when you
                >won't modify after its initialization. ..
                >>
                >So when exactly do I use one or another? Is it *wrong* not use const
                >when I should?
                >>
                Use const when you don't modify the string (or other thing pointed to)
                within the function. constness only applies within the function's scope.
                Outside the variables can be modified, and in fact usually are modified.
                Only rarely is data provided in read-only arrays typed into the program
                directly.
                If this means something, I think it must mean something wrong.
                A const-qualified object is const-qualified, period, whether it is
                in or out of scope. An attempt to modify a const-qualified object
                by name or via a const-qualified pointer requires the compiler to
                issue a diagnostic; an attempt to modify it by other means yields
                undefined behavior. Scope has naught to do with it.
                There's a bit of debate about the virtues of const. One problem is const
                poisoning. Once a pointer becomes const, everything it touches has to be
                const.
                Perhaps you should explain what you mean by "touches." If
                you mean "points at," the claim is wrong: It is entirely all
                right for a pointer-to-const-Thing to point at a Thing that is
                not const-qualified.
                Another problem is that constness applies only to the object
                directly pointed to. However frequently structures contain other
                pointers, and you want to const them as well.
                What do you mean by "to const?" Is it anything like
                "to int" or "to static?"
                So it is not exactly wrong to avoid const. Personally I try to keep it
                to a minimum.
                I almost never use `restrict', because my grasp of precisely
                what it means appears to equal your grasp of `const'. We both
                steer clear of what we don't comprehend.
                However if I am writing code to publish on my website
                const will usually be included for a constant pointer parameter that the
                user provides. If the pointer parameter is returned by another function
                in the same file, however, I usually won't declare it const.
                This may be an accurate description of your habits, but I
                can't see any reason for using or not using `const' based on
                which translation unit a function inhabits.

                --
                Eric Sosman
                esosman@ieee-dot-org.invalid

                Comment

                • =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?=

                  #9
                  Re: When to use const modifier?

                  On Jun 2, 8:11 pm, Leonardo Korndorfer <leokorndor...@ gmail.com>
                  wrote:
                  So when exactly do I use one or another? Is it *wrong* not use const
                  when I should?

                  My motto is to use const WHENEVER you can... unless the const is
                  redudant. The one sole example of it being redundant -- that I'm aware
                  of -- is its use in casts:

                  printf("%d",(in t const)x);

                  Other than that one sole example, I use const EVERYWHERE that I can.

                  Here's how variable definitions work in C:

                  Type variable_name;

                  An example would be:

                  int val;

                  If you want the variable to be const, then you add const to the
                  _type_; it doesn't matter whether you put it first or second, these
                  two are identical:

                  int const val = 5;
                  const int val = 5;

                  Now, if you want to turn a variable into a pointer, then you add an
                  asterisk to the variable's _name_:

                  int *val;

                  If you want the pointer to be const, then you add const to the _name_,
                  and it always goes AFTER the asterisk:

                  int *const val;

                  From there, you can add constness to the "pointed-to type" by adding
                  const to the type name. Again, it doesn't matter whether the const
                  comes before or after the type name:

                  int const *const val;
                  const int *const val;

                  A few random examples would be:

                  int *const val;
                  const int *val;
                  int const *val;
                  int *val;

                  Remember, white space means nothing in C, so you could see these as:

                  int* const val;
                  int*const val;
                  const int* val;
                  int const*val;
                  int* val;
                  int*val;

                  Just remember that the asterisk always goes with the _name_, and if
                  the pointer itself is const then you'll always see the const in the
                  _name_ and it will always be after the asterisk:

                  int *const val;
                  int*const val;
                  int* const val;

                  And then you might see something like:

                  int const* const *const * * * const **p;

                  p is a
                  pointer to
                  pointer to
                  const pointer to
                  pointer to
                  pointer to
                  const pointer to
                  const pointer to
                  const int

                  Of course you could change the white space:

                  int const*const*con st***const**p;

                  The only other change you can make to it, without actually changing
                  the type, is changing the "int const" to "const int" because they're
                  identical:

                  const int *const*const*** const**p;

                  Comment

                  • Keith Thompson

                    #10
                    Re: When to use const modifier?

                    Andrew Kerr <arkerr@gatech. eduwrites:
                    santosh wrote:
                    >Ian Collins wrote:
                    >>Leonardo Korndorfer wrote:
                    >>>I'm litle confused by the const modifier, particularly when use const
                    >Are string literals "real constants", whatever that means? I thought
                    >you
                    >were just supposed to pretend that they were constants, and treat them
                    >as such, to prevent the wrath of UB.
                    >>
                    >
                    Here, C's subtle goals for portability surface. Some memory pages are
                    marked read-only. Any attempted write to a read-only page by a user
                    mode program [contrasted with supervisor mode running the OS's kernel]
                    will result in an interrupt raised by the Memory Management Unit
                    [MMU], the part of the CPU that translates virtual addresses to
                    physical addresses. This interrupt notifies the kernel your program is
                    behaving badly. The default behavior in this case is an abrupt
                    termination known as a "core dump."
                    >
                    Executable files produced by modern linkers are partitioned into
                    segments. The ".data" segment is expected to be read-only and *may* be
                    mapped to a read-only page in virtual memory. Attempting to write it
                    results in the above behavior. This is the meaning of "real constant":
                    the hardware and OS will not permit you to write it after the loader
                    brings that segment into memory and protects the page. String literals
                    are typically placed in the ".data" segment, so treat them as "real
                    constants."
                    The above is all system-specific, and has nothing *directly* to do
                    with C. It's *indirectly* related to C in that (a) it's probably true
                    of many C implementations , and (b) it probably provided some of the
                    motivation for what the C standard actually does (and doesn't)
                    require.
                    This differs somewhat from use of the 'const' keyword. When const is
                    used in a variable definition, the compiler typically attempts to
                    infer its value. If the compiler can guess the initial value at
                    compile time, and by definition the variable's value cannot change
                    after initialization, then it may optimize the value away. That is,
                    replace all instructions loading that variable with load-immediate
                    instructions. If you attempt to take the address of that variable, or
                    the compiler chooses not to get rid of it, it may place that value in
                    the ".data" segment again resulting in a "real constant."
                    "const" really means "read-only". An attempt to modify an object that
                    was declared as "const" invokes undefined behavior. As you say, the
                    compiler is free to use this information to guide optimization.
                    You may implicitly cast a non-const to const.
                    You cannot "implicitly cast" anything to antyhing. The term "cast"
                    refers only to the explicit operator.

                    A value may be implicitly *converted* to a const type.

                    [...]
                    Given a constant variable, you may cast away the const property and
                    then write to it. This is only guaranteed to work if you are certain
                    that the variable was defined as nonconst.
                    It's important to keep in mind that "const" and "constant" are two
                    different things. "const", in C, just means read-only. A "constant"
                    is what some languages refer to as a literal, such as 42, 'x', or 1.2.
                    (And a "constant expression" is one that an implementation is required
                    to be able to evaluate at compilation time.)

                    [snip]

                    --
                    Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                    Nokia
                    "We must do something. This is something. Therefore, we must do this."
                    -- Antony Jay and Jonathan Lynn, "Yes Minister"

                    Comment

                    • Leonardo Korndorfer

                      #11
                      Re: When to use const modifier?

                          const int *const*const*** const**p;
                      Yeah... I'm not sure if someone wants to use a pointer like that
                      one...

                      My point wasn't how to declare, but when to declare.

                      So, I've come to one simple conclusion:
                      One should use const when the content won't be modified anywhere after
                      initialization, and if it will be (and I say that because in "const
                      char*" case my compiler doesn't warn about changin' it), just don't
                      use "const".
                      Sure there can be ways to chage it's data, but those are compiler
                      dependent and doesn't matter for what const means, right?

                      Comment

                      • vippstar@gmail.com

                        #12
                        Re: When to use const modifier?

                        On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
                        Malcolm McLean wrote:
                        So it is not exactly wrong to avoid const. Personally I try to keep it
                        to a minimum.
                        >
                        I almost never use `restrict', because my grasp of precisely
                        what it means appears to equal your grasp of `const'. We both
                        steer clear of what we don't comprehend.
                        Is that true? Wouldn't it be better to just learn what 'const' or
                        'restrict' or X does?

                        Comment

                        • Eric Sosman

                          #13
                          Re: When to use const modifier?

                          vippstar@gmail. com wrote:
                          On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
                          >Malcolm McLean wrote:
                          >>So it is not exactly wrong to avoid const. Personally I try to keep it
                          >>to a minimum.
                          > I almost never use `restrict', because my grasp of precisely
                          >what it means appears to equal your grasp of `const'. We both
                          >steer clear of what we don't comprehend.
                          Is that true? Wouldn't it be better to just learn what 'const' or
                          'restrict' or X does?
                          It would be better, yes. Probably someday I'll set to
                          work to try to remedy my understanding of `restrict', and
                          maybe then I'll find ways to use it intelligently. Until
                          then, I'll just avoid it for fear of using it improperly
                          out of ignorance.

                          I'm suggesting that McLean's avoidance of `const' may be
                          motivated by feelings similar to mine about `restrict': don't
                          mess around with what you don't understand.

                          --
                          Eric Sosman
                          esosman@ieee-dot-org.invalid

                          Comment

                          • Richard

                            #14
                            Re: When to use const modifier?

                            Eric Sosman <esosman@ieee-dot-org.invalidwrit es:
                            vippstar@gmail. com wrote:
                            >On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
                            >>Malcolm McLean wrote:
                            >>>So it is not exactly wrong to avoid const. Personally I try to keep it
                            >>>to a minimum.
                            >> I almost never use `restrict', because my grasp of precisely
                            >>what it means appears to equal your grasp of `const'. We both
                            >>steer clear of what we don't comprehend.
                            >Is that true? Wouldn't it be better to just learn what 'const' or
                            >'restrict' or X does?
                            >
                            It would be better, yes. Probably someday I'll set to
                            work to try to remedy my understanding of `restrict', and
                            maybe then I'll find ways to use it intelligently. Until
                            then, I'll just avoid it for fear of using it improperly
                            out of ignorance.
                            >
                            I'm suggesting that McLean's avoidance of `const' may be
                            motivated by feelings similar to mine about `restrict': don't
                            mess around with what you don't understand.
                            So why dont you bother to actually understand what they do mean?

                            Comment

                            • Eric Sosman

                              #15
                              Re: When to use const modifier?

                              Richard wrote:
                              Eric Sosman <esosman@ieee-dot-org.invalidwrit es:
                              >
                              >vippstar@gmail. com wrote:
                              >>On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
                              >>>Malcolm McLean wrote:
                              >>>>So it is not exactly wrong to avoid const. Personally I try to keep it
                              >>>>to a minimum.
                              >>> I almost never use `restrict', because my grasp of precisely
                              >>>what it means appears to equal your grasp of `const'. We both
                              >>>steer clear of what we don't comprehend.
                              >>Is that true? Wouldn't it be better to just learn what 'const' or
                              >>'restrict' or X does?
                              > It would be better, yes. Probably someday I'll set to
                              >work to try to remedy my understanding of `restrict', and
                              >maybe then I'll find ways to use it intelligently. Until
                              >then, I'll just avoid it for fear of using it improperly
                              >out of ignorance.
                              >>
                              > I'm suggesting that McLean's avoidance of `const' may be
                              >motivated by feelings similar to mine about `restrict': don't
                              >mess around with what you don't understand.
                              >
                              So why dont you bother to actually understand what they do mean?
                              Low priority. First, my limited understanding of
                              `restrict' is that it's mostly an optimizer-enabling hint
                              to the compiler, not something whose addition affects the
                              operation or correctness (or incorrectness) of a program.
                              In this way it's similar to `register', another construct
                              I avoid (but for different reasons). Second, `restrict'
                              doesn't work at all with C89/C90/C95 compilers, and C99
                              compilers (although commoner than they used to be) are
                              still not exactly thick upon the ground.

                              So, when I tackle two-and-a-half pages of Standardese
                              beginning "Let D be a declaration of an ordinary identifier
                              that provides a means of designating an object P as a restrict-
                              qualified pointer to type T," I am not strongly motivated to
                              see the matter through to a conclusion.

                              That's why I "dont" [sic] bother. Not yet, at least.

                              As for `const', I believe my understanding is adequate.
                              On the basis of his posting, I'm suggesting that McLean's may
                              not be.

                              --
                              Eric.Sosman@sun .com

                              Comment

                              Working...