Does this allocate memory?

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

    Does this allocate memory?

    If this is the complete program (ie, the address of the const is never
    taken, only its value used) is it likely the compiler will allocate ram for
    constantA or constantB? Or simply substitute the values in (as would be
    required if I used the hideous, evil, much-abused #define :)

    -----------

    const int constantA = 10;
    static const int constantB = 20;

    void main()
    {
    for( int i=0; i<constantA ; i++ );
    for( int j=0; j<constantB ; j++ );
    }

    ----------

    Thanks in advance :)

    -Curt

  • Alf P. Steinbach

    #2
    Re: Does this allocate memory?

    On Tue, 22 Jul 2003 13:49:30 GMT, Curt <cNurOt@nSoPrth AarMc.com> wrote:
    [color=blue]
    >If this is the complete program (ie, the address of the const is never
    >taken, only its value used) is it likely the compiler will allocate ram for
    >constantA or constantB? Or simply substitute the values in (as would be
    >required if I used the hideous, evil, much-abused #define :)
    >
    >-----------
    >
    >const int constantA = 10;
    >static const int constantB = 20;
    >
    >void main()
    >{
    > for( int i=0; i<constantA ; i++ );
    > for( int j=0; j<constantB ; j++ );
    >}[/color]

    A good compiler will reject this program since it's ill-formed;
    "void main()" is not allowed in a hosted standard C++
    implemented (the term "hosted" is the standard's terminology).

    A not-so-good compiler will reduce the program to nothing since
    it doesn't do anything.

    But in general, any constant takes up memory space if it's used
    at least once. How much is Quality Of Implementation issue.
    Not much more can be said without a more specific context.


    Comment

    • Victor Bazarov

      #3
      Re: Does this allocate memory?

      "Curt" <cNurOt@nSoPrth AarMc.com> wrote...[color=blue]
      > If this is the complete program (ie, the address of the const is never
      > taken, only its value used) is it likely the compiler will allocate ram[/color]
      for[color=blue]
      > constantA or constantB? Or simply substitute the values in (as would be
      > required if I used the hideous, evil, much-abused #define :)
      >
      > -----------
      >
      > const int constantA = 10;
      > static const int constantB = 20;
      >
      > void main()
      > {
      > for( int i=0; i<constantA ; i++ );
      > for( int j=0; j<constantB ; j++ );
      > }
      >
      > ----------[/color]

      It's hard to tell. Existence of 'void main' can force the compiler
      reject the entire program. 'main' always returns 'int'. If that's
      corrected, an optimising compiler will produce code as if the program
      were

      int main() {}

      because the body of the 'main' has no side effects. So, once the
      'main' is made to return 'int', I'd say, no memory is going to be
      allocated.

      Victor


      Comment

      • Curt

        #4
        Re: Does this allocate memory?

        "Victor Bazarov" <v.Abazarov@att Abi.com> wrote in news:vhqgt0eifs 2499
        @corp.supernews .com:
        [color=blue]
        > "Curt" <cNurOt@nSoPrth AarMc.com> wrote...[color=green]
        >> If this is the complete program (ie, the address of the const is never
        >> taken, only its value used) is it likely the compiler will allocate[/color][/color]
        ram[color=blue]
        > for[color=green]
        >> constantA or constantB? Or simply substitute the values in (as would[/color][/color]
        be[color=blue][color=green]
        >> required if I used the hideous, evil, much-abused #define :)
        >>
        >> -----------
        >>
        >> const int constantA = 10;
        >> static const int constantB = 20;
        >>
        >> void main()
        >> {
        >> for( int i=0; i<constantA ; i++ );
        >> for( int j=0; j<constantB ; j++ );
        >> }
        >>
        >> ----------[/color]
        >
        > It's hard to tell. Existence of 'void main' can force the compiler
        > reject the entire program. 'main' always returns 'int'. If that's
        > corrected, an optimising compiler will produce code as if the program
        > were
        >
        > int main() {}
        >
        > because the body of the 'main' has no side effects. So, once the
        > 'main' is made to return 'int', I'd say, no memory is going to be
        > allocated.
        >
        > Victor
        >
        >[/color]

        I'll assume you're not missing my point on purpose, which is, does the
        'static' qualifier compel the compiler to allocate memory for a constant
        that is initialized once at runtime and is only used as a #define might
        be.


        const int constantA = 10;
        static const int constantB = 20;

        int main( int argn, char *argv[] )
        {
        for( volatile int i=0; i<constantA ; i++ );
        for( volatile int j=0; j<constantB ; j++ );

        return 0;
        }


        Comment

        • Peter van Merkerk

          #5
          Re: Does this allocate memory?

          > >> const int constantA = 10;[color=blue][color=green][color=darkred]
          > >> static const int constantB = 20;
          > >>
          > >> void main()
          > >> {
          > >> for( int i=0; i<constantA ; i++ );
          > >> for( int j=0; j<constantB ; j++ );
          > >> }
          > >>
          > >> ----------[/color]
          > >
          > > It's hard to tell. Existence of 'void main' can force the compiler
          > > reject the entire program. 'main' always returns 'int'. If that's
          > > corrected, an optimising compiler will produce code as if the[/color][/color]
          program[color=blue][color=green]
          > > were
          > >
          > > int main() {}
          > >
          > > because the body of the 'main' has no side effects. So, once the
          > > 'main' is made to return 'int', I'd say, no memory is going to be
          > > allocated.[/color][/color]
          [color=blue]
          > I'll assume you're not missing my point on purpose, which is, does the
          > 'static' qualifier compel the compiler to allocate memory for a[/color]
          constant[color=blue]
          > that is initialized once at runtime and is only used as a #define[/color]
          might[color=blue]
          > be.[/color]

          The 'static' keyword does not force the compiler to allocate storage for
          that variable. In fact it would make it easier for the compiler not to
          allocate storage since static variables only accessible within the
          current translation unit. Consequently the compiler can determine with
          100% certainty that a variable is not referenced, thus no storage needs
          to be allocated for it. Storage for non 'static' variables would have to
          be removed by the linker. The fact that the variables in your example
          are declared 'const' and that they are initialized in the same
          translation unit makes it likely that a optimizing compiler simply
          substitutes the variables with their values. In that scenario the
          variables in your code are not referenced, thus no storage is needed for
          those variables. So my guess is that on most decent optimizing compilers
          your program will be optimized to int main(){} without storage for the
          variables.

          However all of this is a quality of implementation issue and your
          compiler&linker may, or may not perform those optimizations. If you
          really want to know if which optimizations are performed take a look at
          the assembly output of the compiler. Note that this output doesn't tell
          you which variables were removed by the linker, so I expect that
          constantA still has storage associated with it according to listing,
          even though it might very well be removed in the linking stage.
          [color=blue]
          > const int constantA = 10;
          > static const int constantB = 20;
          >
          > int main( int argn, char *argv[] )
          > {
          > for( volatile int i=0; i<constantA ; i++ );
          > for( volatile int j=0; j<constantB ; j++ );
          >
          > return 0;
          > }[/color]

          Why are you using volatile for a local variable?

          --
          Peter van Merkerk
          peter.van.merke rk(at)dse.nl



          Comment

          • Victor Bazarov

            #6
            Re: Does this allocate memory?

            "Curt" <cNurOt@nSoPrth AarMc.com> wrote...[color=blue]
            > [...]
            > I'll assume you're not missing my point on purpose, which is, does the
            > 'static' qualifier compel the compiler to allocate memory for a constant
            > that is initialized once at runtime and is only used as a #define might
            > be.[/color]

            'static' has no effect on the constant. Used with a variable
            definition in a global namespace scope, 'static' give it internal
            linkage. However, if memory is not allocated, linkage would have
            no meaning. 'const' allows the compiler not to allocate memory.
            That's the prevailing modifier, I believe. 'static' in this case
            is subordinate.

            Just as with any other 'const', the compiler may decide to allocate
            storage. Or it may decide not to allocate storage.

            If you wrote

            extern const int theanswer = 42;

            then the storage would be allocated for sure. Whether the address
            of that storage will be used when you use 'theanswer' in the same
            unit is also at the discretion of the compiler. It may decide to
            replace any occurrence of 'theanswer' in the code with 42 because
            it's a 'const'.

            Does this answer your question?

            Victor


            Comment

            • Jingz

              #7
              Re: Does this allocate memory?

              [...]

              Thank you for your response.
              [color=blue]
              >[color=green]
              >> const int constantA = 10;
              >> static const int constantB = 20;
              >>
              >> int main( int argn, char *argv[] )
              >> {
              >> for( volatile int i=0; i<constantA ; i++ ); for( volatile int j=0;
              >> j<constantB ; j++ );
              >>
              >> return 0;
              >> }
              >> }[/color]
              > Why are you using volatile for a local variable?
              >[/color]

              Because the original responders wanted to tell me how smart they were
              about proper c++ rather than answer the obvious question in a meaningful
              way. So I composed an equally trivial example that would force code
              generation.

              As a long-time programmer I am sometimes amused (and dismayed) that such
              simple language features ( #define constant 10 ) are universally derided
              by acedemia/language purists who insist on type-safe const's, yet are not
              sure if it will have the same necessary effect of being replaced with the
              literal value.

              c++ took the language in a lot of good directions, but went too far in
              others, the useless defense of cout vs printf for debugging, for example.

              -Curt

              Comment

              • Ron Natalie

                #8
                Re: Does this allocate memory?


                "Jingz" <e@spam.com> wrote in message news:pan.2003.0 7.22.18.13.08.6 50490.432@spam. com...
                [color=blue]
                > As a long-time programmer I am sometimes amused (and dismayed) that such
                > simple language features ( #define constant 10 ) are universally derided
                > by acedemia/language purists who insist on type-safe const's, yet are not
                > sure if it will have the same necessary effect of being replaced with the
                > literal value.[/color]

                It's not typesafety. 10 is of type int just as if you declared it a const int.
                The issue is scoping. What happens when something else in the translation
                unit (perhaps something you didn't write) use the term constant:

                #define constant 10

                struct foo {
                int constant;
                };
                ....

                Perhaps it's just that you don't understand the language well enough.


                Comment

                • Jingz

                  #9
                  Re: Does this allocate memory?

                  On Tue, 22 Jul 2003 14:52:59 -0400, Ron Natalie wrote:

                  [color=blue]
                  > "Jingz" <e@spam.com> wrote in message
                  > news:pan.2003.0 7.22.18.13.08.6 50490.432@spam. com...
                  >[color=green]
                  >> As a long-time programmer I am sometimes amused (and dismayed) that
                  >> such simple language features ( #define constant 10 ) are universally
                  >> derided by acedemia/language purists who insist on type-safe const's,
                  >> yet are not sure if it will have the same necessary effect of being
                  >> replaced with the literal value.[/color]
                  >
                  > It's not typesafety. 10 is of type int just as if you declared it a
                  > const int. The issue is scoping. What happens when something else in
                  > the translation unit (perhaps something you didn't write) use the term
                  > constant:
                  >
                  > #define constant 10
                  >
                  > struct foo {
                  > int constant;
                  > };
                  > ...
                  >
                  > Perhaps it's just that you don't understand the language well enough.[/color]

                  Yes I've seen that argument as well, it is equally contrived. You really
                  have to bend over backwards to show how sane use of #define can be a
                  problem; your example doesn't even compile. A trivial convention like
                  using all capital letters for #defined values is all that would be
                  required.

                  I'm not going to defend such a practice, nor expouse it. The point I have
                  often made when instructing junior programmers fresh out of college is
                  that many textbook problems are solutions to problems that only exist in
                  textbooks.

                  "The real world" is an overused phrase, but maintainability is key. Too
                  often I have read in a trade-journal or commentary about a perfectly
                  reasonable practice that is "bad' becuase some college professor can
                  contrive an example that "breaks" is.

                  Not to open up another can of worms, but inheritance is probobly my
                  favorite example of a good idea gone bad. Everyone agree is it can be
                  over/mis used, but I will content that it is almost never a good idea. It
                  obscures functionality at best, at worst is is an absolutely impenatrable
                  series of tracing back multiple-inheritance spaghetti when a call goes
                  bad and needs to be debugged. 'has a' is far superior, necessitating a
                  dereference and obviating that another block of code is being invoked.
                  "is a" is almost never justified.

                  Sure it allows library building, and has a nice touchy-feely OO, but the
                  fact is it solves a bunch of contrived textbook problems that proper
                  program design not only bypass, but make easier to understand.

                  -Curt

                  Comment

                  • Victor Bazarov

                    #10
                    Re: Does this allocate memory?

                    "Jingz" <e@spam.com> wrote...[color=blue]
                    > [...]
                    > Not to open up another can of worms, but inheritance is probobly my
                    > favorite example of a good idea gone bad. Everyone agree is it can be
                    > over/mis used, but I will content that it is almost never a good idea. It
                    > obscures functionality at best, at worst is is an absolutely impenatrable
                    > series of tracing back multiple-inheritance spaghetti when a call goes
                    > bad and needs to be debugged. 'has a' is far superior, necessitating a
                    > dereference and obviating that another block of code is being invoked.
                    > "is a" is almost never justified.
                    >[/color]

                    I really would like to see you implement polymorphism without
                    inheritance. Or is polymorphism an overrated "touchy-feely OO"
                    as well? Would you like to try this discussion in comp.object?

                    Nobody forces you to use any of the language features. If you
                    think that 'const' is bogus, don't use it. Inheritance is no
                    good? Live without it. What I don't understand is the need to
                    "content" the usability of any feature. Live and let live. Or
                    is the language too complex for you with all that "spaghetti"
                    in it? Could it be that you just need to make an effort and
                    simply learn it?

                    I hope you don't see this as "over/mis used" typing.

                    Victor


                    Comment

                    • Jingz

                      #11
                      Re: Does this allocate memory?

                      I know I can't win, you are in quite authoritative company in terms of
                      people I've argued with about programming paradigms, and I know anyone
                      reading this agrees with you, not me, but I do feel compelled to stick to
                      facts.

                      Microsoft thinks defined like "BOOL" and "WORD" make sense, so I'm not
                      quite sure invoking problems with their source code is credible. I have
                      indeed never seen a sane define collide in the manner you suggest happens
                      "all the time" but if we're going to assume insane programmers then you
                      can prety much claim anything you choose.

                      I certainly agree that c++ promotes code cloarity and maintainability , no
                      question about it, but te fact that it can is often used as a cudgel to
                      beat code with. Complicated multiple inheritance, templates, and bizzare operator
                      overloading are automatically easier to maintain? I think not. They CAN
                      be, but care must be used, as in all programming.

                      -Curt


                      On Tue, 22 Jul 2003 16:18:48 -0400, Ron Natalie wrote:

                      [color=blue]
                      > "Jingz" <e@spam.com> wrote in message
                      > news:pan.2003.0 7.22.20.11.56.6 39734.23156@spa m.com...
                      >[color=green]
                      >> Yes I've seen that argument as well, it is equally contrived.[/color]
                      >
                      > It's not contrived at all. If you've never seen it, you've never
                      > managed a large project where more than one organization wrote parts of
                      > the code.
                      >[color=green]
                      >> You really
                      >> have to bend over backwards to show how sane use of #define can be a
                      >> problem;[/color]
                      >
                      > I didn't bend over backwards. This stuff happens all the time. It's
                      > a perennial problem with Microsoft include files for example.
                      >[color=green]
                      >> I'm not going to defend such a practice, nor expouse it. The point I
                      >> have often made when instructing junior programmers fresh out of
                      >> college is that many textbook problems are solutions to problems that
                      >> only exist in textbooks.[/color]
                      >
                      > Sorry, just because YOU have never seen the problem, doesn't mean they
                      > shouldn't exist. Do you advocate telling drivers to not fasten their
                      > seatbelts because you've never been in an accident?
                      >[color=green]
                      >> "The real world" is an overused phrase, but maintainability is key.[/color]
                      >
                      > Precisely. Using C++ constructs promotes maintainability .[/color]

                      Comment

                      • Jingz

                        #12
                        Re: Does this allocate memory?

                        > Nobody forces you to use any of the language features. If you think[color=blue]
                        > that 'const' is bogus, don't use it. Inheritance is no good? Live
                        > without it. What I don't understand is the need to "content" the
                        > usability of any feature. Live and let live. Or is the language too
                        > complex for you with all that "spaghetti" in it? Could it be that you
                        > just need to make an effort and simply learn it?[/color]

                        Indeed, if all you took away from my posts was "inheritanc e is no good"
                        then one of us does need to take more time and study, and its you.

                        -Curt

                        Comment

                        • Victor Bazarov

                          #13
                          Re: Does this allocate memory?

                          "Jingz" <e@spam.com> wrote...[color=blue][color=green]
                          > > I really would like to see you implement polymorphism without
                          > > inheritance. Or is polymorphism an overrated "touchy-feely OO" as well?[/color]
                          >
                          > Would be delighted to, show me the example.[/color]

                          I don't think you deserve it, considering the tone you've taken.

                          class DrawContext;

                          class Window
                          {
                          set<Window*> child_windows;
                          public:
                          virtual void draw(const DrawContext&) = 0;
                          void addChildWindow( Window* pw)
                          {
                          child_windows.p ush_back(pw);
                          }
                          };

                          class OpenGLWindow : virtual public Window
                          {
                          void draw(const DrawContext&);
                          };

                          class ToolbarWindow : virtual public Window
                          {
                          void draw(const DrawContext&);
                          };

                          class ThreeDToolbarWi ndow : public ToolbarWindow, OpenGLWindow
                          {
                          ...
                          };

                          class MainWindow : public Window
                          {
                          public:
                          MainWindow(cons t string&);
                          void draw(const DrawContext&);
                          };

                          ....

                          class MySpecialMainWi ndow : public MainWindow
                          {
                          public:
                          MySpecialMainWi ndow(const string& title) :
                          MainWindow(titl e)
                          {
                          addChildWindow( new ThreeDToolbarWi ndow);
                          }
                          };

                          void Window::draw(co nst DrawContext& dc)
                          {
                          set<Window*>::i terator kid_it = child_windows.b egin();
                          while (kid_it != child_windows.e nd())
                          {
                          (*kid_it)->draw(dc);
                          ++kid_it;
                          }
                          }

                          .... Why do I bother? ...

                          Victor


                          Comment

                          • Alexander Terekhov

                            #14
                            Re: Does this allocate memory?


                            Victor Bazarov wrote:
                            [color=blue]
                            > ... Why do I bother? ...[/color]

                            Founded in 1828, the University of Lancashire is a leading university recognised in QS World Rankings. Study with us in Preston, Burnley, Cumbria or Cyprus.

                            (see "fixation -> anal personality")

                            regards,
                            alexander.

                            Comment

                            • Jingz

                              #15
                              Re: Does this allocate memory?

                              This is not a complete example, this is a code snippet from a larger
                              system that assumes this functionality is available. Since its clearly
                              from a very large system I don't think its feasible to show you how it
                              could be implemented in a far easier to maintain and less obscure way.

                              What am I talking about? Well, for example, everything thats important
                              happens as the result of a side-effect of calling "draw". Since the code
                              is not declarative, you have to hope the implementor thought of
                              everything when they wrote their piece of the class.

                              Since, of course, they didn't, you're going to have to go spelunking
                              through an endless list of header files to find the implementation, and
                              heaven forbid the original design was flawed, and critical information
                              was not passed back to a class back at layer 2 or 3. I've seen that and
                              its not pretty.

                              -Curt


                              On Tue, 22 Jul 2003 16:53:37 -0400, Victor Bazarov wrote:
                              [color=blue]
                              > class DrawContext;
                              >
                              > class Window
                              > {
                              > set<Window*> child_windows;
                              > public:
                              > virtual void draw(const DrawContext&) = 0; void
                              > addChildWindow( Window* pw)
                              > {
                              > child_windows.p ush_back(pw);
                              > }
                              > };
                              >
                              > class OpenGLWindow : virtual public Window {
                              > void draw(const DrawContext&);
                              > };
                              >
                              > class ToolbarWindow : virtual public Window {
                              > void draw(const DrawContext&);
                              > };
                              >
                              > class ThreeDToolbarWi ndow : public ToolbarWindow, OpenGLWindow {
                              > ...
                              > };
                              >
                              > class MainWindow : public Window
                              > {
                              > public:
                              > MainWindow(cons t string&);
                              > void draw(const DrawContext&);
                              > };
                              >
                              > ...
                              >
                              > class MySpecialMainWi ndow : public MainWindow { public:
                              > MySpecialMainWi ndow(const string& title) :
                              > MainWindow(titl e)
                              > {
                              > addChildWindow( new ThreeDToolbarWi ndow);
                              > }
                              > };
                              >
                              > void Window::draw(co nst DrawContext& dc) {
                              > set<Window*>::i terator kid_it = child_windows.b egin(); while (kid_it
                              > != child_windows.e nd()) {
                              > (*kid_it)->draw(dc);
                              > ++kid_it;
                              > }
                              > }
                              > }[/color]

                              Comment

                              Working...