473,761 Members | 4,421 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Jul 19 '05 #1
37 4671
On Tue, 22 Jul 2003 13:49:30 GMT, Curt <cN****@nSoPrth AarMc.com> wrote:
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.
Jul 19 '05 #2
"Curt" <cN****@nSoPrth AarMc.com> wrote...
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
Jul 19 '05 #3
"Victor Bazarov" <v.********@att Abi.com> wrote in news:vhqgt0eifs 2499
@corp.supernews .com:
"Curt" <cN****@nSoPrth AarMc.com> wrote...
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


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;
}
Jul 19 '05 #4
> >> 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.

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?

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

Jul 19 '05 #5
"Curt" <cN****@nSoPrth AarMc.com> wrote...
[...]
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
Jul 19 '05 #6
[...]

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

Jul 19 '05 #7

"Jingz" <e@spam.com> wrote in message news:pa******** *************** *********@spam. com...
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.
Jul 19 '05 #8
On Tue, 22 Jul 2003 14:52:59 -0400, Ron Natalie wrote:

"Jingz" <e@spam.com> wrote in message
news:pa******** *************** *********@spam. com...
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.


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

Jul 19 '05 #9
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:

"Jingz" <e@spam.com> wrote in message
news:pa******** *************** ***********@spa m.com...
Yes I've seen that argument as well, it is equally contrived.


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.
You really
have to bend over backwards to show how sane use of #define can be a
problem;


I didn't bend over backwards. This stuff happens all the time. It's
a perennial problem with Microsoft include files for example.
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.


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?
"The real world" is an overused phrase, but maintainability is key.


Precisely. Using C++ constructs promotes maintainability .


Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3670
by: Alan Gifford | last post by:
I wrote a program to make sure that new would throw a bad_alloc exception if more memory was requested than was available. On my system, new allocates up to 2931 MBs of memory (I don't have that much, not even with swap) before throwing an exception. When the program tries to fill in the allocated memory with data, it is killed after using up the available memory. Does anyone know why the exception is not being thrown until well after...
4
2590
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
9
3733
by: R.Z. | last post by:
i was wondering whether it pays off in terms of memory use to maintain lots of empty deques (it would be convenient for my algorithms but memory use is more important). and does the size of a deque depends on the size of its members even if the deque is empty? is there at all a way to check out how much memory my deque occupies? i've read that the sizeof operator cannot be used with dynamically allocated arrays so i figured it wouldn't give...
74
4046
by: Suyog_Linux | last post by:
I wish to know how the free()function knows how much memory to be freed as we only give pointer to allocated memory as an argument to free(). Does system use an internal variable to store allocated memory when we use malloc(). Plz help......
6
2316
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always reference a correct/valid structure member upon that allocated memory? If I allocate memory, for example like this way:
3
1797
by: Nadav | last post by:
Hi, I am writing a mixed mode application, I have a mixed mode Assembly manipulating a managed byte array, to access this array in unmanaged code I '__pin' the array, As I understand, pining an object guarantee that it will not be collected by the GC ( by increasing it's refcount or so ), Taking that in mind, looking at the code generated by the compiler I can't see anything taking care of the GC refcount... following is the pinned variable...
5
4716
by: Allen | last post by:
I wrote many classes. In a class, there is a member variable which is declared as char szMTreeBuf. On both Windows XP and VxWorks, it cannot work. Then I try to declare the member variable as static char szMTreeBuf, it can work again. But when add some other function codes, it cannot run normally. I modify the class delearation, and change szMTreeBuf member variable to be local variable. Again it can run now. Why does C++ program run...
5
8092
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space assigned to <pointerby "new". Does "new" create a list of pointer names and the size of the memory array they point to? I also read that some compilers may store the number of consec mem locations a pointer points to, just before the first data...
9
8179
by: rohits123 | last post by:
I have an overload delete operator as below ////////////////////////////////// void operator delete(void* mem,int head_type) { mmHead local_Head = CPRMemory::GetMemoryHead(head_type); mmFree(&local_Head,(char *)mem); CPRMemory::SetMemoryHeadAs(local_Head,head_type); } ///////////////////// void* operator new(size_t sz, int head_Type) {
0
9353
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9975
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9909
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9788
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8794
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6623
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3889
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2765
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.