Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. How rigorous are you about using const?

How rigorous are you about using const?

Scheduled Pinned Locked Moved Solved C++ Gurus
34 Posts 11 Posters 5.5k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • JonBJ Offline
    JonBJ Offline
    JonB
    wrote on last edited by
    #1

    I started programming in C before it even had const :embarrassed:

    Now that I'm trying to be a good C++ citizen: I know when I must and must not use const on methods and, say, member variables. But what about on, say, temporary variables like follows.

    For example I like to keep my code typing/mistakes down to minimum. So I'll create temporaries for multiple references to longer sequences

    QWidget *widg = memberVarable->something.something;
    QWidget *widg = otherClass->someMethod(abc, def);
    z = widg->something;
    widg->someMethod()
    

    (QWidget is only an example, could be anything.) Now, let's imagine that in either case the source widget variable/method result is not declared const, it could be used for consty or non-consty things. But the code I will be using here happens to only need to deal with it consty, at least so far.

    You know what's coming: how rigorous/zealous/religious are you about remembering to declare your temp variable const while you're developing your code? It's another 6 characters to (remember to) type, I find myself often not thinking to do so, to be welcomed into C++-land should I make more effort to do so?

    K 1 Reply Last reply
    0
    • JonBJ JonB

      I started programming in C before it even had const :embarrassed:

      Now that I'm trying to be a good C++ citizen: I know when I must and must not use const on methods and, say, member variables. But what about on, say, temporary variables like follows.

      For example I like to keep my code typing/mistakes down to minimum. So I'll create temporaries for multiple references to longer sequences

      QWidget *widg = memberVarable->something.something;
      QWidget *widg = otherClass->someMethod(abc, def);
      z = widg->something;
      widg->someMethod()
      

      (QWidget is only an example, could be anything.) Now, let's imagine that in either case the source widget variable/method result is not declared const, it could be used for consty or non-consty things. But the code I will be using here happens to only need to deal with it consty, at least so far.

      You know what's coming: how rigorous/zealous/religious are you about remembering to declare your temp variable const while you're developing your code? It's another 6 characters to (remember to) type, I find myself often not thinking to do so, to be welcomed into C++-land should I make more effort to do so?

      K Offline
      K Offline
      koahnig
      wrote on last edited by koahnig
      #2

      @JonB

      You have a compile error with your code above ;)

      Personally I see const simply as a help/assistence to avoid nasty hard to find changes of content of members.
      So probably I will not end up in C++ heaven.

      My question would if "const" helps in some savings during execution?

      BTW I started first with FORTRAN IV and punching cards. That is embarrassing. :)

      [koahnig: edited]

      Vote the answer(s) that helped you to solve your issue(s)

      sierdzioS JonBJ 2 Replies Last reply
      0
      • K koahnig

        @JonB

        You have a compile error with your code above ;)

        Personally I see const simply as a help/assistence to avoid nasty hard to find changes of content of members.
        So probably I will not end up in C++ heaven.

        My question would if "const" helps in some savings during execution?

        BTW I started first with FORTRAN IV and punching cards. That is embarrassing. :)

        [koahnig: edited]

        sierdzioS Offline
        sierdzioS Offline
        sierdzio
        Moderators
        wrote on last edited by
        #3

        @koahnig said in How rigorous are you about using const?:

        My question would if "const" helps in some savings during execution?

        That's one thing to consider. One "gotcha" here is that you'll need to know when compiler can optimize const stuff and when not. IMO it's easier to use it everywhere and compiler will figure it out :P

        Another thing to consider is:

        should it be possible to modify this value? If another developer (or you next week) modifies this code, can they break something silently by modifying this value?

        In either case, if answer is "yes", const should be added, I think.

        I tend to pepper my code with const absolutely everywhere but I don't think it's a sane approach. I guess it's just easier for me to apply it everywhere and not thing about whether it's really needed or not :P

        (Z(:^

        1 Reply Last reply
        1
        • K koahnig

          @JonB

          You have a compile error with your code above ;)

          Personally I see const simply as a help/assistence to avoid nasty hard to find changes of content of members.
          So probably I will not end up in C++ heaven.

          My question would if "const" helps in some savings during execution?

          BTW I started first with FORTRAN IV and punching cards. That is embarrassing. :)

          [koahnig: edited]

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by JonB
          #4

          @koahnig said in How rigorous are you about using const?:

          BTW I started first with FORTRAN IV and punching cards.

          OMG! OK, I feel like a youngster now... ;-)

          @sierdzio
          Remember, I am not asking about member variables/methods, where you need to get your const right. I am talking about: I have a non-const something to which I want to point a temporary, local variable, and I turn out only to be needing to do const things through this variable. Do you never/sometimes/always bother to make your temp var const, just because you feel like it's good practice? Personally I don't care about any efficiency of code generated here.

          sierdzioS 1 Reply Last reply
          0
          • JonBJ JonB

            @koahnig said in How rigorous are you about using const?:

            BTW I started first with FORTRAN IV and punching cards.

            OMG! OK, I feel like a youngster now... ;-)

            @sierdzio
            Remember, I am not asking about member variables/methods, where you need to get your const right. I am talking about: I have a non-const something to which I want to point a temporary, local variable, and I turn out only to be needing to do const things through this variable. Do you never/sometimes/always bother to make your temp var const, just because you feel like it's good practice? Personally I don't care about any efficiency of code generated here.

            sierdzioS Offline
            sierdzioS Offline
            sierdzio
            Moderators
            wrote on last edited by
            #5

            @JonB said in How rigorous are you about using const?:

            @koahnig said in How rigorous are you about using const?:

            BTW I started first with FORTRAN IV and punching cards.

            OMG! OK, I feel like a youngster now... ;-)

            @sierdzio
            Remember, I am not asking about member variables/methods, where you need to get your const right. I am talking about: I have a non-const something to which I want to point a temporary, local variable, and I turn out only to be needing to do const things through this variable. Do you never/sometimes/always bother to make your temp var const, just because you feel like it's good practice? Personally I don't care about any efficiency of code generated here.

            Yes, I know you talk about local temporaries. I always use const for those. But I don't have any strong argument for it.

            (Z(:^

            1 Reply Last reply
            1
            • fcarneyF Offline
              fcarneyF Offline
              fcarney
              wrote on last edited by
              #6

              @sierdzio said in How rigorous are you about using const?:

              But I don't have any strong argument for it.

              There is strong evidence of avoiding mutable global variables due to tracking down the code that made the change that breaks everything else. So one could make the argument that a similar problem could occur within a function scope as well. Reducing mutability probably helps reduce certain classes of bugs. I was introduced to this concept in python. The reason python has comprehensions (list, dict, etc) is to reduce variable usage in loops. Variable uses in loops in supposed to be a source of a certain class of bugs. I also see functional programmers going to extremes to reduce mutability as well. Though I am unclear as to all the reasons for that. I have spent of fair amount of time trying to internalize FP concepts and still don't understand the why of FP. My main problem has been that a loop designed using an imperative approach can easily take 3 or 4 loops in FP. Whatever, I do think reducing mutability can help reasoning about a problem, which is why they do this. To enforce that constraint. There is probably a dissertation somewhere about this.

              C++ is a perfectly valid school of magic.

              1 Reply Last reply
              0
              • JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by JonB
                #7

                OK, since we're on a roll, let's push the boat out!

                Do you bother to put const against simple value types in, say, formal parameters of a function?

                void person_function(const int age, const double weight, const bool is_female)
                {
                    const int next_birthday = age + 1;
                    if (! is_female)
                        qDebug() << next_birthday << weight / age;
                }
                

                If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

                K 1 Reply Last reply
                1
                • JonBJ JonB

                  OK, since we're on a roll, let's push the boat out!

                  Do you bother to put const against simple value types in, say, formal parameters of a function?

                  void person_function(const int age, const double weight, const bool is_female)
                  {
                      const int next_birthday = age + 1;
                      if (! is_female)
                          qDebug() << next_birthday << weight / age;
                  }
                  

                  If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

                  K Offline
                  K Offline
                  koahnig
                  wrote on last edited by
                  #8

                  @JonB said in How rigorous are you about using const?:

                  OK, since we're on a roll, let's push the boat out!

                  Do you bother to put const against simple value types in, say, formal parameters of a function?

                  void person_function(const int age, const double weight, const bool is_female)
                  {
                      const int next_birthday = age + 1;
                      if (! is_female)
                          qDebug() << next_birthday << weight / age;
                  }
                  

                  If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

                  Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

                  Vote the answer(s) that helped you to solve your issue(s)

                  JonBJ sierdzioS 2 Replies Last reply
                  1
                  • K koahnig

                    @JonB said in How rigorous are you about using const?:

                    OK, since we're on a roll, let's push the boat out!

                    Do you bother to put const against simple value types in, say, formal parameters of a function?

                    void person_function(const int age, const double weight, const bool is_female)
                    {
                        const int next_birthday = age + 1;
                        if (! is_female)
                            qDebug() << next_birthday << weight / age;
                    }
                    

                    If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

                    Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #9

                    @koahnig
                    Yep, that's fine by me! I just wanted to know what you C++-long-timers do/don't do :)

                    1 Reply Last reply
                    0
                    • Chris KawaC Offline
                      Chris KawaC Offline
                      Chris Kawa
                      Lifetime Qt Champion
                      wrote on last edited by Chris Kawa
                      #10

                      I believe that adding const on parameters passed by value is a bit of a language design problem.
                      It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
                      And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

                      class Foo {
                          void Bar(int);
                      };
                      
                      void Foo::Bar(const int) {}
                      

                      so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

                      As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

                      EDIT: Scratch that. I mixed it with another pattern :P

                      K 1 Reply Last reply
                      2
                      • mrjjM Offline
                        mrjjM Offline
                        mrjj
                        Lifetime Qt Champion
                        wrote on last edited by
                        #11

                        Hi
                        I never used it for temp variables or by copy parameters as the gain seems slim.
                        However, const is vital for protecting data from being modified by a sub-function and
                        also to clearly state in an interfaces that a function will not alter your data.

                        Btw. It could be fun to develop some test cases to validate the decades old saying that const allows the
                        compiler to optimize the code as we never really saw any speed gains during profiling.
                        Not saying its not true, but at least with 3 different compilers for embedded development, the
                        profiler showed no speed gains with const.

                        1 Reply Last reply
                        0
                        • K koahnig

                          @JonB said in How rigorous are you about using const?:

                          OK, since we're on a roll, let's push the boat out!

                          Do you bother to put const against simple value types in, say, formal parameters of a function?

                          void person_function(const int age, const double weight, const bool is_female)
                          {
                              const int next_birthday = age + 1;
                              if (! is_female)
                                  qDebug() << next_birthday << weight / age;
                          }
                          

                          If so, I think I'll want a const key on my keyboard because I'm going to be typing it so often!

                          Personally that would be too much const here. Certainly it does not harm, but it is completely useless in the parameter list, because it is to the exterior const anyhow. I could see only some advantages for rather large routines, when you need to ensure that you are not accidentially changing the variable.

                          sierdzioS Offline
                          sierdzioS Offline
                          sierdzio
                          Moderators
                          wrote on last edited by
                          #12

                          @koahnig said in How rigorous are you about using const?:

                          void person_function(const int age, const double weight, const bool is_female)

                          I started using const also in parameters after I joined one project where it was the convention.

                          It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

                          (Z(:^

                          K 1 Reply Last reply
                          0
                          • Chris KawaC Chris Kawa

                            I believe that adding const on parameters passed by value is a bit of a language design problem.
                            It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
                            And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

                            class Foo {
                                void Bar(int);
                            };
                            
                            void Foo::Bar(const int) {}
                            

                            so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

                            As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

                            EDIT: Scratch that. I mixed it with another pattern :P

                            K Offline
                            K Offline
                            koahnig
                            wrote on last edited by
                            #13

                            @Chris-Kawa said in How rigorous are you about using const?:

                            I believe that adding const on parameters passed by value is a bit of a language design problem.
                            It's a copy, so adding const in the interface of the function exposes details of internal implementation of the function - you know it won't be modified inside, but you shouldn't have to know that. If you're giving the function a copy it's not your business whether it modifies the copy or not. You're not getting it back after all. On the other hand you might want that const internally and adding it in the param declaration is the only way. So there's a bit of a problem - you don't want that const externally but you do want it internally.
                            And here it gets hairy, because a little known fact about C++ is that this is perfectly valid:

                            class Foo {
                                void Bar(int);
                            };
                            
                            void Foo::Bar(const int) {}
                            

                            so you can legally eat cake and have cake at the same time. But this is so obscure and unexpected that you don't see that done in practice. Personally I just don't use const here.

                            As for const on local parameters - I use it not on some principle or for possible optimizations but for far more trivial reasons. I work on a massive code base and using const on locals is a great way to catch interface bugs.

                            EDIT: Scratch that. I mixed it with another pattern :P

                            I would not be concerned about implementation details presented to the outside. At the day's end you could use it to stray wrong assumptions to people trying to interpret such details. If you want tohide you can and will hide implementation details. The easiest way is using a const reference to the input parameter and use the reference only. No cost after compilation to my understanding.

                            Vote the answer(s) that helped you to solve your issue(s)

                            1 Reply Last reply
                            0
                            • sierdzioS sierdzio

                              @koahnig said in How rigorous are you about using const?:

                              void person_function(const int age, const double weight, const bool is_female)

                              I started using const also in parameters after I joined one project where it was the convention.

                              It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

                              K Offline
                              K Offline
                              koahnig
                              wrote on last edited by
                              #14

                              @sierdzio said in How rigorous are you about using const?:

                              @koahnig said in How rigorous are you about using const?:

                              void person_function(const int age, const double weight, const bool is_female)

                              I started using const also in parameters after I joined one project where it was the convention.

                              It does have some merits - when implementing a function, you do expect the input parameter to have the same value. But when it's not const, you can modify and forget that you did so, leading to bugs. But again, it's not a strong argument or a big issue.

                              If there is a project with that rule, I would simply follow. Sometimes there is no need to have useless time-consuming fights.
                              As I have stated larger routines may have sometimes the issue, that you need to ensure to the input value to the end. However, I would not do it directly through a const in the parameter list.

                              @mrjj said in How rigorous are you about using const?:

                              Btw. It could be fun to develop some test cases to validate the decades old saying that const allows the
                              compiler to optimize the code as we never really saw any speed gains during profiling.
                              Not saying its not true, but at least with 3 different compilers for embedded development, the
                              profiler showed no speed gains with const.

                              I would be really interested to see construct where you can verify cpu consumption advantages of const. Whenever I have tried to see such advantages it always ended with cannot decide. However, that might be a compiler implementation issue.

                              Vote the answer(s) that helped you to solve your issue(s)

                              1 Reply Last reply
                              0
                              • Kent-DorfmanK Offline
                                Kent-DorfmanK Offline
                                Kent-Dorfman
                                wrote on last edited by
                                #15

                                The stench of const will permiate a class structure and make it a royal PITA to get things to compile with brain dead enhanced warnings all enabled...but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers who feel they need to stifle true creativity with "safety rules" to given them some feeling of control over things they really don't understand.

                                When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it...Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle where you spend more time documenting why you cannot do something than actually solving programming problems with creative and elegant solutions....I really need to retire.

                                Chris KawaC 1 Reply Last reply
                                0
                                • Kent-DorfmanK Kent-Dorfman

                                  The stench of const will permiate a class structure and make it a royal PITA to get things to compile with brain dead enhanced warnings all enabled...but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers who feel they need to stifle true creativity with "safety rules" to given them some feeling of control over things they really don't understand.

                                  When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it...Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle where you spend more time documenting why you cannot do something than actually solving programming problems with creative and elegant solutions....I really need to retire.

                                  Chris KawaC Offline
                                  Chris KawaC Offline
                                  Chris Kawa
                                  Lifetime Qt Champion
                                  wrote on last edited by
                                  #16

                                  @Kent-Dorfman:

                                  but that's what happens when a traditionally artistic field turns into assembly line work governed by poor programmers

                                  You seem angry :) Const was not invented as a tool to keep poor programmers in check. It was introduced by quite smart people that recognized reoccurring problems of mutability in ever growing code bases. When you work with multi-million line project it's simply impossible to hold every dependency and restriction in your head and immutability is a great tool to help with that. There's nothing mandatory about it. Like any other tool you use it as you see fit, but it's been demonstrated time and again that restricting mutability of the system lifts its quality quite a lot. If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                                  @Kent-Dorfman:

                                  When C++ was very Cish and I could treat memory as I saw fit, but had some nice OO additions, I liked it

                                  Nothing changed in that regard in C++. You can still play with bits, bytes, alignment, paging etc. There are more restrictions for memory access these days but they are imposed on the OS level, not language level and that's mostly because malware and internet. I'm sure it's obvious to you that exposing entire raw memory to a small utility in a server cluster or to any program in an ever online world is a bad idea.

                                  @Kent-Dorfman:

                                  Modern C++ (especially in commercial environments) is more of a SCRUM boondoggle

                                  Maybe you just picked the wrong project then? They are not all the same. The one I'm working on at least sure doesn't feel like that. And we don't use SCRUM :)

                                  @Kent-Dorfman:

                                  I really need to retire.

                                  Or just a break to recharge your batteries and a project that better fits your liking? Cheer up. It's not all doom and gloom ;)

                                  1 Reply Last reply
                                  3
                                  • mrjjM Offline
                                    mrjjM Offline
                                    mrjj
                                    Lifetime Qt Champion
                                    wrote on last edited by
                                    #17

                                    @Chris-Kawa said i

                                    If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                                    This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                                    So please run for c++ committee,so i can vote for you 😋

                                    Chris KawaC sierdzioS 2 Replies Last reply
                                    2
                                    • mrjjM mrjj

                                      @Chris-Kawa said i

                                      If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                                      This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                                      So please run for c++ committee,so i can vote for you 😋

                                      Chris KawaC Offline
                                      Chris KawaC Offline
                                      Chris Kawa
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #18

                                      @mrjj said:

                                      This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.
                                      So please run for c++ committee,so i can vote for you

                                      Haha, thanks, but it's just not gonna happen in C++. It's far too late and adding it even as an option would just ugly split the community. Imagine you have a large project which uses it and want to use a small utility library that doesn't They're incompatible on interface level. Bummer.

                                      mrjjM 1 Reply Last reply
                                      0
                                      • Chris KawaC Chris Kawa

                                        @mrjj said:

                                        This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.
                                        So please run for c++ committee,so i can vote for you

                                        Haha, thanks, but it's just not gonna happen in C++. It's far too late and adding it even as an option would just ugly split the community. Imagine you have a large project which uses it and want to use a small utility library that doesn't They're incompatible on interface level. Bummer.

                                        mrjjM Offline
                                        mrjjM Offline
                                        mrjj
                                        Lifetime Qt Champion
                                        wrote on last edited by
                                        #19

                                        @Chris-Kawa
                                        Hehe yeah i know in practice it would be hard to manage but on the other hand, we survived
                                        years of template hell where you were never sure if the compiler would support it and still today
                                        c++ is not a uniform thing between compiler vendors even it has become much better.

                                        So i still think it would be great for new projects and 5 years later many of the lib you would use, would be compilable with this on.

                                        But yeah its a 99% pipe dream.

                                        1 Reply Last reply
                                        0
                                        • mrjjM mrjj

                                          @Chris-Kawa said i

                                          If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                                          This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                                          So please run for c++ committee,so i can vote for you 😋

                                          sierdzioS Offline
                                          sierdzioS Offline
                                          sierdzio
                                          Moderators
                                          wrote on last edited by
                                          #20

                                          @mrjj said in How rigorous are you about using const?:

                                          @Chris-Kawa said i

                                          If it were up to me I'd make const the default and only declare mutable things that I know need to change (just with a shorter keyword than mutable maybe).

                                          This i wanted of for decades. It would break a lot of code but if it was a compile flag/opt in then it could work.

                                          So please run for c++ committee,so i can vote for you 😋

                                          Oh, +1 to that :D

                                          (Z(:^

                                          1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved