Does this allocate memory?

C

Curt

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++ );
}
 
A

Alf P. Steinbach

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++ );
}

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.
 
V

Victor Bazarov

Curt said:
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++ );
}

----------

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
 
C

Curt

ram

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

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;
}
 
P

Peter van Merkerk

const int constantA = 10;
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.

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.
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;
}

Why are you using volatile for a local variable?
 
V

Victor Bazarov

Curt said:
[...]
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.

'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
 
J

Jingz

[...]

Thank you for your response.
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;
}
}
Why are you using volatile for a local variable?

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
 
R

Ron Natalie

Jingz said:
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.

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.
 
J

Jingz

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.

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
 
V

Victor Bazarov

Jingz said:
[...]
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.

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
 
J

Jingz

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
 
J

Jingz

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?

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

-Curt
 
V

Victor Bazarov

Jingz said:
Would be delighted to, show me the example.

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.push_back(pw);
}
};

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

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

class ThreeDToolbarWindow : public ToolbarWindow, OpenGLWindow
{
...
};

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

....

class MySpecialMainWindow : public MainWindow
{
public:
MySpecialMainWindow(const string& title) :
MainWindow(title)
{
addChildWindow(new ThreeDToolbarWindow);
}
};

void Window::draw(const DrawContext& dc)
{
set<Window*>::iterator kid_it = child_windows.begin();
while (kid_it != child_windows.end())
{
(*kid_it)->draw(dc);
++kid_it;
}
}

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

Victor
 
J

Jingz

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
 
J

Jingz

Jingz said:
[...]
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 contend 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.
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

In terms of "the tone I've taken" I have been factual, substantive and
non-confrontational. You on the other hand, seem to want a simple
difference in opinion to be a personal attack against me with fairly rude
and immature innuendo.

-Curt
 
P

Peter van Merkerk

Jingz said:
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.

The Microsoft Windows API is written for C compilers somewhere in the
eighties, they could not use C++ features. The choices they made do not
always make sense from a C++ point of view. Besides that Microsoft does not
always make the best possible technical decisions. Short macro names like
"BOOL" and "WORD" are likely to clash. The reason that they don't clash
that often in reality is that most programmers know that those names are
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.

What you say may make sense for small projects, but with large complicated
projects the rules change. Problems that might seem accademic in one
context, may become a very real problems in another context. For example if
you use multiple 3rd party libraries or work on a large projects, name
clashes are not all that uncommon. I'm not making this up, I'm speaking from
personal experience. The usual workaround for these problems is using a
prefix for macro names. But what if two 3rd party libraries have name
clashes? In that case you are in deep shit I can tell you. Sure you can
modify the header files. But that means maintaining your own version of that
header file. Every time a new version of the library is released you will
have to do the modifications again. This can become quite a headache, and
therefore one should be extremely reluctant to do so.

Namespaces provide a much more elegant and scalable solution for the name
clash problem than prefixes. However preprocessor symbols don't care about
namespaces. Neither prefixes nor namespaces guarantee that you won't have
name clashes, but they do diminish the change you will get one.
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.

I absolutely agree with the last sentence. C++ is a very powerful
programming language; in the right hands wonderful things can be done with
it, but in the wrong hands it is more like letting a monkey play with a gun.
In general I think the designers of the C++ made pragmatic decisions. Most
features in the language are there for a (good) reason, even if they don't
seem make all that much sense at first.
 
J

Jingz

Jingz said:
[...]
In terms of "the tone I've taken" I have been factual [..]

Which part in your "inheritance obscures functionality at best" tirade
is factual?

A call to someFunct(); that is not found in the implementation/header file of
the class you are on, is either global or (more probobly, in a
well-formed project, an inherited class)

In order to understand that program you must now track down which class
its in, and in the case of multiple inheritance this can become quite
annoying. Of course in a codebase you are very famliar with, or perhaps
one you wrote yourself, this is not a big deal; in a large project or in
maintaining a new set of code it becomes a very big deal. It also, I
believe, fits a reasonable definition of "obscuring".

Consider now the case of m_3dWidget->someFunc(); by making it a 'has a'
reference, you pinpoint exactly where it is.

-Curt
 
K

Karl Heinz Buchegger

Jingz said:
[...]

Thank you for your response.
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;
}
}
Why are you using volatile for a local variable?

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.

But that loops still does no work other then consuming CPU time.
An optimizer might drop them.
 
K

Karl Heinz Buchegger

Jingz said:
Jingz said:
[...]
In terms of "the tone I've taken" I have been factual [..]

Which part in your "inheritance obscures functionality at best" tirade
is factual?

A call to someFunct(); that is not found in the implementation/header file of
the class you are on, is either global or (more probobly, in a
well-formed project, an inherited class)

In order to understand that program you must now track down which class
its in, and in the case of multiple inheritance this can become quite
annoying. Of course in a codebase you are very famliar with, or perhaps
one you wrote yourself, this is not a big deal; in a large project or in
maintaining a new set of code it becomes a very big deal. It also, I
believe, fits a reasonable definition of "obscuring".

Right. And?
That's why we are professinoals and get paid for it. If every teeny weeny
newbie could do that we wouldn't earn our money. Building a rocket technically
isn't very distinct from buildind a bicycle. You use the same tools. And yet
building a rocket is incredible more complex then building a bike and one
needs to take care of much more things. That's why rocket engineers earn
much more money, they know how to do it and more importantly: they can do it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top