Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[homework-problem] Code within.

1 view
Skip to first unread message

John Meyer

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to
Hi guys. I've got a problem for a C++ class. The problem is
this: using only conio.h, type and accept three sentences of eighty
characters or less. The catch is that you can't print anything
between parentheses marks to the screen.

here's the code I got:

#include <conio.h>
//John Meyer
//Intro to C++
//Dr. Knight
//10/03/1998

void main()
{
char typed;
int char_count=0, sent_count;

for (sent_count = 0; sent_count <3; sent_count++)
{
while (typed != '\r' && char_count <= 80)
{ //Begin while loop
typed=getche();
if (typed == '(')
{ //Begin if loop
putch('\b');
while (typed != ')')
{
typed = getch();
}
} //End if loop
else
{
char_count = char_count + 1;
}
} //End while loop
typed='a'; //Clear out the typed and
char_count variables.
char_count=0;
putch('\n'); //Force the cursor to the
next line.
} //end for loop
}


This works, but my instructor, when he handed out this problem,
_implied_ that there was a simpler code for this? Is there. Note, I
don't need code per se, just ideas.

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]
[ about comp.lang.c++.moderated. First time posters: do this! ]

hu...@anubisinc.com

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to
In article <3616ec04...@news.rmi.net>,

john_...@geocities.com (John Meyer) wrote:
> Hi guys. I've got a problem for a C++ class. The problem is
> this: using only conio.h, type and accept three sentences of eighty
> characters or less. The catch is that you can't print anything
> between parentheses marks to the screen.
>

you could decide to get your characters without echo and only display the
character when it's outside '()' by using a bool variable (or a integer if
you want to nest parentheses). you avoid the inner loop, and you won't have
to output backspaces. It's also easy to support () matching (what does your
program do when you type in two open parentheses?)

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

Jack Klein

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
On 6 Oct 1998 07:57:43 -0400, john_...@geocities.com (John Meyer) wrote:

> Hi guys. I've got a problem for a C++ class. The problem is
> this: using only conio.h, type and accept three sentences of eighty
> characters or less. The catch is that you can't print anything
> between parentheses marks to the screen.

<Jack>

I said it before and I'll say it again, your instructor, or whoever decides
the contents of your course, is an idiot. If you are taking a course in C++
they should be teaching C++ and not non-standard compiler specific crap.

</Jack>

Kendall Beaman

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
John Meyer wrote:

> Hi guys. I've got a problem for a C++ class. The problem is
> this: using only conio.h, type and accept three sentences of eighty
> characters or less. The catch is that you can't print anything
> between parentheses marks to the screen.
>

Ok. What do you mean by simpler code? You want to do this using less
lines or something? Not sure what you mean but if you're looking to maybe
optimize your code you might see if you can do it with one loop and using
fewer lines. I can send you some code if you like and show you what I
mean.

Of course the teacher could mean that yours does more than what he was
intending which would be perfectly fine with me. :)

Here's a couple of questions you may want to ask about this assignment:

1. Do I have to limit the sentences to 80?
2. Am I required to have error checking to insure sentences are 80
characters or less.

If the answer is no to those two questions then one way to make your code
"simpler" would be to make a loop that simply asks for a char and prints
it out. There would be only three chars that you'd need to check for and
do something about. The newline and the parenthesis.

>
> here's the code I got:
>
> #include <conio.h>
> //John Meyer
> //Intro to C++
> //Dr. Knight
> //10/03/1998
>
> void main()

I gotta say it. I just gotta. This is an incorrect declaration of main
according to C++ as well as the C ANSI standard. I know many examples in
books and textbooks do it but its still incorrect. I try to nip this in
the bud early before it becomes a habit. :)

> {
> char typed;
> int char_count=0, sent_count;
>
> for (sent_count = 0; sent_count <3; sent_count++)
> {
> while (typed != '\r' && char_count <= 80)
> { //Begin while loop
> typed=getche();
> if (typed == '(')
> { //Begin if loop
> putch('\b');
> while (typed != ')')
> {
> typed = getch();
> }
> } //End if loop
> else
> {
> char_count = char_count + 1;
> }
> } //End while loop
> typed='a'; //Clear out the typed and
> char_count variables.
> char_count=0;
> putch('\n'); //Force the cursor to the
> next line.
> } //end for loop
> }
>
> This works, but my instructor, when he handed out this problem,
> _implied_ that there was a simpler code for this? Is there. Note, I
> don't need code per se, just ideas.
>

> [ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]
> [ about comp.lang.c++.moderated. First time posters: do this! ]

Let me know if you'd like me to send you a little code snippet or
something.
--
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

If you ask for nothing then nothing is probably what you'll get. If you
ask for everything
then chances are you may get something.
-------------------------------------------------------------------------------------------

"And the Lord spake unto the Angel that guarded the eastern gate, saying
Where is the
flaming sword which was given unto thee? And the Angel said, I had it
here only a
moment ago, I must have put it down some where, forget my own head next.

And the Lord did not ask him again."
"Good Omens" by Terry Pratchett & Neil
Gaiman
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

john_...@my-dejanews.com

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
In article <361AB18C...@mindspring.com>,

Kendall Beaman <bea...@mindspring.com> wrote:
> John Meyer wrote:
>
> > Hi guys. I've got a problem for a C++ class. The problem is
> > this: using only conio.h, type and accept three sentences of eighty
> > characters or less. The catch is that you can't print anything
> > between parentheses marks to the screen.
> >
>
> Ok. What do you mean by simpler code? You want to do this using less
> lines or something? Not sure what you mean but if you're looking to maybe
> optimize your code you might see if you can do it with one loop and using
> fewer lines. I can send you some code if you like and show you what I
> mean.
>

Yes, it worked, I just handed it in. BTW, this got posted multiple times by
my mail reader, something which I just figured out how to prevent.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Kendall Beaman

unread,
Oct 8, 1998, 3:00:00 AM10/8/98
to
Jack Klein wrote:

> On 6 Oct 1998 07:57:43 -0400, john_...@geocities.com (John Meyer) wrote:
>
> > Hi guys. I've got a problem for a C++ class. The problem is
> > this: using only conio.h, type and accept three sentences of eighty
> > characters or less. The catch is that you can't print anything
> > between parentheses marks to the screen.
>

> <Jack>
>
> I said it before and I'll say it again, your instructor, or whoever decides
> the contents of your course, is an idiot. If you are taking a course in C++
> they should be teaching C++ and not non-standard compiler specific crap.
>

You know, I thought this way at first before I posted my reply. I was going to
ask him why in the world in a C++ class wouldn't he be learning C++ specific
stuff. I had gotten all set to tell him to look at iostreams and the like,
however, upon reflection I realized that he is in a BEGINNING C++ class. These
classes do tend to be the same early on as their C counterparts but they get
into C++ specific features later on. Keep in mind that some of the students
don't know C first. We tend to look at it from an advanced C programmer's
perspective. You have to start at the beginning, not jump straight into
iostreams and all that. You have people taking those classes that don't know
what a pointer is. How can you start teaching them about multiple inheritance
and so forth.

So, we just have to remember that the class is an intro to programming utilizing
C++ rather than a C++ class for C programmers. There is a major difference.

>
> </Jack>


>
> [ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]
> [ about comp.lang.c++.moderated. First time posters: do this! ]


--
-=-=-=-=-=-=-=-=-=-=-Web Site: http://www2.andrews.edu/~beaman-=-=-==-=-=-=-


If you ask for nothing then nothing is probably what you'll get. If you ask
for everything then chances are you may get something.

A Very Special Friend of Mine
-=-=-=-=-=-=-=-=-=-=-Web Site: http://www2.andrews.edu/~beaman-=-=-==-=-=-=-

Stan Brown

unread,
Oct 9, 1998, 3:00:00 AM10/9/98
to
bea...@mindspring.com (Kendall Beaman) wrote:

>Jack Klein wrote:
>> I said it before and I'll say it again, your instructor, or whoever decides
>> the contents of your course, is an idiot. If you are taking a course in C++
>> they should be teaching C++ and not non-standard compiler specific crap.

I uttered a heartfelt "Amen!" because Klein put my thoughts into words,
eloquently.

>You know, I thought this way at first before I posted my reply. I was going to
>ask him why in the world in a C++ class wouldn't he be learning C++ specific
>stuff. I had gotten all set to tell him to look at iostreams and the like,
>however, upon reflection I realized that he is in a BEGINNING C++ class. These
>classes do tend to be the same early on as their C counterparts but they get
>into C++ specific features later on.

Fair enough, and I might agree with you if it were stdio.h that the
problem was using. But conio.h? It's neither standard C++ nor standard C.
It's used *far* less often than stdio.h or iostreams, so I still see no
justification for wasting time on it in an introductory course.

--
Stan Brown, Oak Road Systems, Cleveland, Ohio, USA
http://www.concentric.net/%7eBrownsta/
My reply address is correct as is. The courtesy of providing a correct
reply address is more important to me than time spent deleting spam.

ajen...@javanet.com

unread,
Oct 9, 1998, 3:00:00 AM10/9/98
to
In article <361B90A2...@mindspring.com>,

Kendall Beaman <bea...@mindspring.com> wrote:
> Jack Klein wrote:
>
> > On 6 Oct 1998 07:57:43 -0400, john_...@geocities.com (John Meyer) wrote:
> >
> > > Hi guys. I've got a problem for a C++ class. The problem is
> > > this: using only conio.h, type and accept three sentences of eighty
> > > characters or less. The catch is that you can't print anything
> > > between parentheses marks to the screen.
> >
> > <Jack>
> >
> > I said it before and I'll say it again, your instructor, or whoever decides
> > the contents of your course, is an idiot. If you are taking a course in C++
> > they should be teaching C++ and not non-standard compiler specific crap.
> >
..SNIP..

> perspective. You have to start at the beginning, not jump straight into
> iostreams and all that. You have people taking those classes that don't know
> what a pointer is. How can you start teaching them about multiple inheritance
> and so forth.
>
> So, we just have to remember that the class is an intro to programming
utilizing
> C++ rather than a C++ class for C programmers. There is a major difference.

Do you think

-- helloworld.c --
#include <stdio.h>

int main(int argc, char **argv)
{
printf("Hello World!\n");
return 0;
}
-- end --

is easier for a beginner than

-- helloworld.cpp --
#include <iostream>

int main(int argc, char **argv)
{
std::cout << "Hello World\n";
return 0;
}
-- end --

I personally think they'd both take about the same amount of explaining to a
beginner. I agree that you shouldn't try to teach multiple inheritance in the
first lesson, or maybe even inheritance at all, but I don't see why you can't
start right off using C++. In any case, conio.h isn't even standard C, let
alone C++.

--
Adam P. Jenkins
ajen...@javanet.com

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Phlip

unread,
Oct 9, 1998, 3:00:00 AM10/9/98
to
Kendall Beaman wrote:

>Jack Klein wrote:
>
>> I said it before and I'll say it again, your instructor, or whoever
decides
>> the contents of your course, is an idiot. If you are taking a course
in C++
>> they should be teaching C++ and not non-standard compiler specific
crap.

>...So, we just have to remember that the class is an intro to


programming utilizing
>C++ rather than a C++ class for C programmers. There is a major
difference.

Authors like Bjarne Stroustrup and Steve Heller have reported success
starting on 'main' and '::std::string' in the first class or chapter.
This puts the details inside the class where they can be ignored, and
gets the students focussed on solving problems.

Teaching C on the first weeks of a C++ course compares to teaching
Visual Basic by, on the first day, manipulating 'BSTR's as 'Long's
returned from 'SysAllocString ()'. Start teaching on the easiest and
most direct way to get things done.

-- Phlip at politizen dot com (address munged)
======= http://users.deltanet.com/~tegan/home.html =======
-- The lunatics have stock options in the asylum --

Alex Martelli

unread,
Oct 9, 1998, 3:00:00 AM10/9/98
to
Kendall Beaman wrote in message <361B90A2...@mindspring.com>...
[snip]

>don't know C first. We tend to look at it from an advanced C programmer's
>perspective. You have to start at the beginning, not jump straight into
>iostreams and all that. You have people taking those classes that don't know
>what a pointer is. How can you start teaching them about multiple inheritance
>and so forth.


I strongly disagree: I am convinced that the best way to teach
"beginning programming" using C++ (which would not be my
language of choice for that specific task, but, oh well) is to
present at first higher-level concepts, getting into lower-level,
more difficult ones only gradually if at all.

USING iostreams, at a beginner's level, is EASY -- EASIER
than using stdio (let alone silly proprietary non-portable stuff
like conio!). Sure, they don't know what a pointer is -- well,
they don't have to learn it yet, to input an integer from cin;
they WOULD have to learn it FIRST, to read it with scanf!

I think in such a course (assuming a typical 150 hours for
lessons, plus exercises) one would not get very far into
either lower-level stuff ("how do I _implement_ all of this
wonderful stuff that I've been _using_ so far"?) nor very
advanced C++ (multiple inheritance, virtual inheritance,
partial specialization of templates, ...); my guess is that
pointers would have to be introduced (they're just too
useful for even pretty simple stuff!), but not builtin arrays
(std::vector will do just fine, thanks), nor union, nor
struct (let them use class for everything), nor, probably,
anything in the preprocessor except for #include; they'd
get a little way along in learning to define their own simple
classes and templates, and get a pretty complete
coverage of using (but not extending) the simpler
parts of the C++ Standard Library (I probably wouldn't
mention, say, deques -- sort of specialized, I guess --
but [using namespace std:-)] vector, list, string, set,
map, most of their members, probably the multi kinds
as well, and most of the algorithms; probably not locales
and facets, but several kinds of streams and most of
their members). Hopefully this would leave some time
to introduce the most fundamental principles of design
including a few crucial patterns and idioms.

If you start delving into not strictly needed low-level
stuff, I think you're doing your students a disservice,
because, given time constraints, you won't then be
able to do justice to more important parts. I will
admit that I've never taught a 1st programming course
in C++, but I've done both "halves" separately --
taught 1st programming courses (using Pascal,
and using Fortran -- getting across the concept of
an abstract data type in Fortran 77 was "fun":-),
and taught C++ to people new to the language (but
middling to experienced programmers otherwise).

Any comments from people who HAVE had the
real-world experience of teaching a 1st programming
course in C++, would of course be welcome...!


Alex

Kendall Beaman

unread,
Oct 10, 1998, 3:00:00 AM10/10/98
to
Stan Brown wrote:

> Fair enough, and I might agree with you if it were stdio.h that the
> problem was using. But conio.h? It's neither standard C++ nor standard C.
> It's used *far* less often than stdio.h or iostreams, so I still see no
> justification for wasting time on it in an introductory course.
>

I agree with you there. As I said I was of the same mind as Klein. If I
were
teaching a C++ class for people who know nothing about C or programming I
would
most likely start out with a more C++ flavor as opposed to C but I just
understand
that most of these beginning classes don't do that.

My personal opinion as to why is that most of the instructors are C
programmers who
have learned C++.

--
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


If you ask for nothing then nothing is probably what you'll get. If you ask
for everything then chances are you may get something.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Kendall Beaman

unread,
Oct 10, 1998, 3:00:00 AM10/10/98
to
Phlip wrote:

> Authors like Bjarne Stroustrup and Steve Heller have reported success
> starting on 'main' and '::std::string' in the first class or chapter.
> This puts the details inside the class where they can be ignored, and
> gets the students focussed on solving problems.
>

As long as they do ignore those details everything is fine.

>
> Teaching C on the first weeks of a C++ course compares to teaching
> Visual Basic by, on the first day, manipulating 'BSTR's as 'Long's
> returned from 'SysAllocString ()'. Start teaching on the easiest and
> most direct way to get things done.

I agree, although since C is still a major force in the industry some
exposure to it would be useful. But I agree with you. In a C++ course you
shouldn't teach straight C. I was really talking more about advanced C++
features quickly. Doing something simple with cout and the like would be
just fine.

Only think is that "easiest" is relative. As for direct well that's not
always the best or not possible. The focus should be on problem solving as
you said before using C++ (Since its a C++ class) as a medium.

Kendall Beaman

unread,
Oct 10, 1998, 3:00:00 AM10/10/98
to
Alex Martelli wrote:

> Kendall Beaman wrote in message <361B90A2...@mindspring.com>...
> [snip]
> >don't know C first. We tend to look at it from an advanced C programmer's
> >perspective. You have to start at the beginning, not jump straight into
> >iostreams and all that. You have people taking those classes that don't know
> >what a pointer is. How can you start teaching them about multiple inheritance
> >and so forth.
>
> I strongly disagree: I am convinced that the best way to teach
> "beginning programming" using C++ (which would not be my
> language of choice for that specific task, but, oh well) is to
> present at first higher-level concepts, getting into lower-level,
> more difficult ones only gradually if at all.
>

*smile* You are disagreeing but I do not believe we are in disagreement. First off
you said beginning programming. That's is a whole different ballgame. See my
comments in the Java replacing C++ thread. I too would most likely not
chose C++
for such a class. However we were talking about a beginning C++ class. Not a
beginning programming class. And unfortunately there is a distinction.
Also please
note my reference to multiple inheritance. I was referring to jumping into
advanced C++.

Let me clarify my position. If I were teaching a beginning C++ class then
everything I did would have a C++ bend to it. If I were teaching a beginning
programming class my emphasis would be on programming concepts and the like.

My previous comments were only to clarify why I see that most beginning C++
classes tend to resemble and mimic beginning C classes. I can understand
why this
is but that doesn't mean I would do this myself.

> USING iostreams, at a beginner's level, is EASY -- EASIER
> than using stdio (let alone silly proprietary non-portable stuff
> like conio!). Sure, they don't know what a pointer is -- well,
> they don't have to learn it yet, to input an integer from cin;
> they WOULD have to learn it FIRST, to read it with scanf!
>

I'll have to disagree with you there. They do not have to learn it to use
scanf.
Just like you would do with C++ and not go into details you can do that
same. In
fact I was using scanf (which I really really hated) and the like before
I ever
heard of a pointer. Also, terms like easy and easier are always relative
so I try
not to use them.

> [snip]

>
> If you start delving into not strictly needed low-level
> stuff, I think you're doing your students a disservice,
> because, given time constraints, you won't then be
> able to do justice to more important parts. I will
> admit that I've never taught a 1st programming course
> in C++, but I've done both "halves" separately --
> taught 1st programming courses (using Pascal,
> and using Fortran -- getting across the concept of
> an abstract data type in Fortran 77 was "fun":-),
> and taught C++ to people new to the language (but
> middling to experienced programmers otherwise).
>

You might find this link interesting.

http://www.cs.rochester.edu/u/martin/book/web-prospectus.html

It talks about C++ as a first programming language. The author does
believe that
it's best to bite the bullet and do it but there are problems associated
with it
but its still worth it. Also since C is a subset of C++ I feel that it
would also
be an injustice to completely ignore that subset. You might not want to
spend a
whole lot of time on it but I think a little would be enough.

Scott Ellsworth

unread,
Oct 12, 1998, 3:00:00 AM10/12/98
to
In article <361EC38A...@mindspring.com>, Kendall Beaman
<bea...@mindspring.com>
<362ee7e4....@netnews.worldnet.att.net>
<361B90A2...@mindspring.com>

<MPG.1086c457e...@news.concentric.net> wrote:
>Stan Brown wrote:
>> Fair enough, and I might agree with you if it were stdio.h that the
>> problem was using. But conio.h? It's neither standard C++ nor standard C.
>> It's used *far* less often than stdio.h or iostreams, so I still see no
>> justification for wasting time on it in an introductory course.

> I agree with you there. As I said I was of the same mind as Klein. If I
> were teaching a C++ class for people who know nothing about C or


> programming I would most likely start out with a more C++ flavor as
> opposed to C but I just understand that most of these beginning
> classes don't do that.

In an intro class, I would rather they teach STANDARD C or C++, over
extensions. Whether the instructor taught with a C or a C++ flavor is
not as important, in my opinion, as thier bad decision to use
nonstandard code. (Perhaps they did point out that this is a compiler
specific extension and we were not told that, but just like most intro
classes do not teach in C++, they do not even know when things are
non standard.)

I would be just as annoyed with the nameless intro teacher had he or
she started with an MS extension to C++. Both are evil in an intro
class, precisely because the stuednts are not yet in a position to
know that they are being taught a nonstandard library.

I have taught C++ classes using PowerPlant, a Mac-only framework, but
then the class focus was explicitly GUI apps on a Mac.

Scott

Scott Ellsworth sc...@eviews.com
"When a great many people are unable to find work, unemployment
results" - Calvin Coolidge, (Stanley Walker, City Editor, p. 131 (1934))
"The barbarian is thwarted at the moat." - Scott Adams

Kendall Beaman

unread,
Oct 13, 1998, 3:00:00 AM10/13/98
to
On 12 Oct 1998 21:07:13 -0400, sc...@eviews.com (Scott Ellsworth)
wrote:

::In article <361EC38A...@mindspring.com>, Kendall Beaman
[snip]

::In an intro class, I would rather they teach STANDARD C or C++, over


::extensions. Whether the instructor taught with a C or a C++ flavor is
::not as important, in my opinion, as thier bad decision to use
::nonstandard code. (Perhaps they did point out that this is a compiler

I agree 100%. Actually when the original poster asked his question my
mind actually skipped over the fact that only conio.h was allowed. I'd
already started writing a sample program using iostreams. Then I
noticed that and just stared at it for a while wondering what in the
heck the teacher was thinking but I tried to give them the benefit of
the doubt.

::specific extension and we were not told that, but just like most intro


::classes do not teach in C++, they do not even know when things are
::non standard.)

Definitely. Not once in my entire college life did we have an
assignment that restricted us to using a non standard header. We were
allowed to use it if we wanted to but usually by that time we knew
enough to know what we were doing but they didn't have it as part of
our curriculum.

::
::I would be just as annoyed with the nameless intro teacher had he or

::she started with an MS extension to C++. Both are evil in an intro
::class, precisely because the stuednts are not yet in a position to
::know that they are being taught a nonstandard library.

Again agree. I'll tell you. I have always felt a bit inferior in my
C++ skills because when I was in college they didn't teach it and I've
never had any formal training. Some years ago I decided it was time to
learn it so I grabbed Bjarne's book as well as one called "Teach
yourself ANSI C++ in 21 days" or something like that. I read them and
then read them again. They inevitably I came online and asked
questions and sent e-mail with questions. Then I went and bought Scott
Meyers' books.

After seeing what is being taught in the schools I don't know if I
came out ahead or not. I mean granted I've been programming in C for
10+ years and learned C++ after I was already an experienced C
programmer but still. I actually talked to a guy who is now getting
his Masters and when we switched compilers he was completely lost
because they taught him too many compiler specific things without
telling him. It was really sad. I was actually told that when you
declare a global variable to be static that it initializes that
variable to zero. :(
[snip]
::
::Scott

David Kastrup

unread,
Oct 13, 1998, 3:00:00 AM10/13/98
to
bea...@mindspring.com (Kendall Beaman) writes:

> After seeing what is being taught in the schools I don't know if I
> came out ahead or not. I mean granted I've been programming in C for
> 10+ years and learned C++ after I was already an experienced C
> programmer but still. I actually talked to a guy who is now getting
> his Masters and when we switched compilers he was completely lost
> because they taught him too many compiler specific things without
> telling him. It was really sad. I was actually told that when you
> declare a global variable to be static that it initializes that
> variable to zero. :(

Actually, uninitialized variables with static linkage have been
guaranteed to be initialized to zero in even the first versions of C
as defined by Kernighan/Ritchie.

I should be very much surprised if any standards team would have dared
to change this, but having no standard available myself, I cannot
qualifiedly comment.

--
David Kastrup Phone: +49-234-700-5570
Email: d...@neuroinformatik.ruhr-uni-bochum.de Fax: +49-234-709-4209
Institut für Neuroinformatik, Universitätsstr. 150, 44780 Bochum, Germany

Victor Bazarov

unread,
Oct 14, 1998, 3:00:00 AM10/14/98
to
David Kastrup wrote in message ...

>bea...@mindspring.com (Kendall Beaman) writes:
>
>> After seeing what is being taught in the schools I don't know if I
>> came out ahead or not. I mean granted I've been programming in C for
>> 10+ years and learned C++ after I was already an experienced C
>> programmer but still. I actually talked to a guy who is now getting
>> his Masters and when we switched compilers he was completely lost
>> because they taught him too many compiler specific things without
>> telling him. It was really sad. I was actually told that when you
>> declare a global variable to be static that it initializes that
>> variable to zero. :(
>
>Actually, uninitialized variables with static linkage have been
>guaranteed to be initialized to zero in even the first versions of C
>as defined by Kernighan/Ritchie.
>
>I should be very much surprised if any standards team would have dared
>to change this, but having no standard available myself, I cannot
>qualifiedly comment.


Give you a hand here:

The Draft Standard, section 3.6.2 Initialization of non-local
objects: "The storage for objects with static storage duration
(3.7.1) shall be zero-intialized (8.5) before any other
initialization takes place." The same source, section
6.7 Declaration statement, paragraph 4: "The zero-initialization
(8.5) of all local objects with static storage duration (3.7.1)
is performed before any other initialization takes place."

And again, I am pretty sure they didn't change it in the final
version.

Victor
--
Please remove underscores from my address when replying by mail

Kendall Beaman

unread,
Oct 14, 1998, 3:00:00 AM10/14/98
to
David Kastrup wrote:

> bea...@mindspring.com (Kendall Beaman) writes:
>
> > After seeing what is being taught in the schools I don't know if I
> > came out ahead or not. I mean granted I've been programming in C for
> > 10+ years and learned C++ after I was already an experienced C
> > programmer but still. I actually talked to a guy who is now getting
> > his Masters and when we switched compilers he was completely lost
> > because they taught him too many compiler specific things without
> > telling him. It was really sad. I was actually told that when you
> > declare a global variable to be static that it initializes that
> > variable to zero. :(
>
> Actually, uninitialized variables with static linkage have been
> guaranteed to be initialized to zero in even the first versions of C
> as defined by Kernighan/Ritchie.
>
> I should be very much surprised if any standards team would have dared
> to change this, but having no standard available myself, I cannot
> qualifiedly comment.
>

You might be right. Its been quite a while but I do remember that
different
compilers handled this differently. I remember being told that some
compilers
initialized uninitialized globals to zero but I'd never heard that
static
would force or ensure this behavior. Then again it was a long time ago
and
back then I most likely dealt with non-standard compilers and since I
was
taught to always initialize my variables I wouldn't really know. But one
thing that was sad about the situation I mentioned above is that they
didn't
know what static really did. You mention static linkage to them and they
would have looked at you blankly.

I wrote this little program and compiled it under VC++.

#include <iostream>

static int x;

int main (void)
{

std::cout << x << std::endl;

return 0;
}

The result was that it printed out a zero. Ok cool. But then I removed
the
static keyword and it still printed out zero. So now I'm curious. What
does
the standard for C/C++ actually say about this?

> --
> David Kastrup Phone:
+49-234-700-5570
> Email: d...@neuroinformatik.ruhr-uni-bochum.de Fax:
+49-234-709-4209
> Institut für Neuroinformatik, Universitätsstr. 150, 44780 Bochum,
Germany
>

> [ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]
> [ about comp.lang.c++.moderated. First time posters: do this! ]


--
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-=-=-=-=-=

If you ask for nothing then nothing is probably what you'll get. If you
ask
for everything then chances are you may get something.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-=-=-=-=-=

Ron Natalie

unread,
Oct 14, 1998, 3:00:00 AM10/14/98
to
Kendall Beaman wrote:


Unfortuantely, static is one of those much abused keywords
in C++.

> I wrote this little program and compiled it under VC++.
>
> #include <iostream>
>
> static int x;
>
> int main (void)
> {
>
> std::cout << x << std::endl;
>
> return 0;
> }
>
> The result was that it printed out a zero. Ok cool. But then I removed
> the
> static keyword and it still printed out zero. So now I'm curious. What
> does
> the standard for C/C++ actually say about this?
>
>

Which is as it should be. Where you see a difference is inside
a block:

int main() {
static int x;


std::cout << x << std::endl;
}

will print a zero, where

int main() {
int x;


std::cout << x << std::endl;
}

has undefined results.

John Nagle

unread,
Oct 14, 1998, 3:00:00 AM10/14/98
to
"Victor Bazarov" <v_bazarov@j_ps.net> writes:
>The Draft Standard, section 3.6.2 Initialization of non-local
>objects: "The storage for objects with static storage duration
>(3.7.1) shall be zero-intialized (8.5) before any other
>initialization takes place." The same source, section
>6.7 Declaration statement, paragraph 4: "The zero-initialization
>(8.5) of all local objects with static storage duration (3.7.1)
>is performed before any other initialization takes place."

The sad thing is why it has to be that way. The order of
execution of static constructors is not inherently safe. So some
objects need a "have I been constructed yet" flag. That flag has
to be initialized to some known value before construction.
Thus the early zeroing of static objects.

The right answer was a link-time dependency sort for
static objects, like Modula II, but the old-line UNIX people
are terrified of changing the linker. Thus the language acquires
another unsafe hack.

John Nagle

Kendall Beaman

unread,
Oct 15, 1998, 3:00:00 AM10/15/98
to
Victor Bazarov wrote:

> David Kastrup wrote in message ...
> >bea...@mindspring.com (Kendall Beaman) writes:

> [snip]

> >
> >Actually, uninitialized variables with static linkage have been
> >guaranteed to be initialized to zero in even the first versions of C
> >as defined by Kernighan/Ritchie.
> >
> >I should be very much surprised if any standards team would have dared
> >to change this, but having no standard available myself, I cannot
> >qualifiedly comment.
>

> Give you a hand here:
>

> The Draft Standard, section 3.6.2 Initialization of non-local
> objects: "The storage for objects with static storage duration
> (3.7.1) shall be zero-intialized (8.5) before any other
> initialization takes place." The same source, section
> 6.7 Declaration statement, paragraph 4: "The zero-initialization
> (8.5) of all local objects with static storage duration (3.7.1)
> is performed before any other initialization takes place."
>

> And again, I am pretty sure they didn't change it in the final
> version.
>
> Victor

Wow. You learn something new all the time. I LOVE programming. Anyway, I'd
better go to a few people who would appreciate it and tell them this. I
always taught them to initialize their variables and to avoid globals
unless they were absolutely sure it was necessary. In all the years I'd
been programming I've always initialized non-local objects so I never had
reason to learn of this. Thanks for the clarification guys!

David Kastrup

unread,
Oct 15, 1998, 3:00:00 AM10/15/98
to
Kendall Beaman <bea...@mindspring.com> writes:

[static storage initialized to zero]

> Wow. You learn something new all the time. I LOVE programming. Anyway,
I'd
> better go to a few people who would appreciate it and tell them this.
I
> always taught them to initialize their variables and to avoid globals
> unless they were absolutely sure it was necessary.

Avoiding globals is in most circumstances a good idea, anyhow. Of
course, fixed tables are somewhat an exception, but even then it is
often a good idea to give them static linkage.

> In all the years I'd been programming I've always initialized
> non-local objects so I never had reason to learn of this. Thanks for
> the clarification guys!

While principally not making a difference, there might be some
compilers that put explicitly initialized variables (even if
initialized to zero) into the initialized data segment. Which means
that the operating system has to load them in from disk at program
start, instead of just clearing them to zero in one block.

Don't expect any noticeable difference, though.

--
David Kastrup Phone:
+49-234-700-5570
Email: d...@neuroinformatik.ruhr-uni-bochum.de Fax:
+49-234-709-4209
Institut für Neuroinformatik, Universitätsstr. 150, 44780 Bochum,
Germany

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Mungo Henning

unread,
Oct 15, 1998, 3:00:00 AM10/15/98
to
Kendall Beaman wrote:
[static set to zero snipped]

> I
> always taught them to initialize their variables and to avoid globals
> unless they were absolutely sure it was necessary.

For my sins I teach C and C++ courses, and I point out that linkers used
to union the space for uninitialised globals:
fileA.c: int i;
fileB.c: double i;
Now compile each file individually and then link and, assuming a 4 byte
int and
an 8 byte double, the size taken in the executable was 8 bytes with the
first four of these for the int and the whole eight for the double...
yeuch!
Luckily the linker refused to 'union' two variables which each had been
initialised (even if they were initialised to the same value), hence the
rule in the company I worked for was to initialise every global.
Judicious use
of 'nm' on Unix followed by a swift use of 'awk' highlighted any
uninitialised
globals.

Now that's my experience of C, but what of C++ nowadays: is this still a
problem?

> In all the years I'd
> been programming I've always initialized non-local objects so I never
had
> reason to learn of this.

I'd reason that its safer to initialise everything and then relax this
(if
speed becomes an issue).

Just my tuppence worth.

Mungo Henning

P.S. My rules for global variables (having been bitten badly by the damn
things)
include using long unambiguous names and requiring that the name of the
creator be left in a comment beside the global so that they could be
shot
later... ;-)
I guess namespaces are the saviour for this problem, but it sure made
life
interesting in C when your boss decided to declare three variables in a
header
(which was
#included in EVERY source file) whose type was 'int' and whose names
were 'i',
'j'
and 'k'... 'for' loops were never so interesting... :-)

Kendall Beaman

unread,
Oct 15, 1998, 3:00:00 AM10/15/98
to
Alan Bellingham wrote:

> bea...@mindspring.com (Kendall Beaman) wrote:
>
> > It was really sad. I was actually told that when you
> >declare a global variable to be static that it initializes that
> >variable to zero. :(
>

> You mean, Stroustrup is _wrong_?
>

*smirk* I doubt it. :)

>
> (CPL 3rd, 9.4.1)
>

See my other post. Basically I was a victim of early non-standard
conforming
compilers and since I was always taught that because of these compilers
I
should always initialize any non-local objects I never had cause to
question
that or to see if it was the compilers that were at fault.

When I got to this job I'd been apalled at the fact that they used the
static keyword just so they didn't have to initialize their variables.
Obviously it worked but I'd told them that they shouldn't do that and
that
different compilers might do different things and that it was "safer" to
initialize them. I also, incorrectly, told them that it wasn't ANSI C.
But
even after 10 years I still learn. I LOVE Programming. *grin*

Kendall Beaman

unread,
Oct 16, 1998, 3:00:00 AM10/16/98
to
Mungo Henning wrote:

> Kendall Beaman wrote:
> [static set to zero snipped]

> [snip]
>

> Now that's my experience of C, but what of C++ nowadays: is this still a
> problem?
>

Not sure. With C++ I still have the mentality of initializing everything and
with constructors I can ensure that this is the case. At least for user
defined types. I don't usually mess with the built-in ones.

> > In all the years I'd
> > been programming I've always initialized non-local objects so I never
> had
> > reason to learn of this.
>
> I'd reason that its safer to initialise everything and then relax this
> (if
> speed becomes an issue).
>
> Just my tuppence worth.
>

I agree. I will always advocate initializing everything as being safer. If
the programmer knows enough about the particular platform or application and
feels that its faster not to then go for it but with the computers today it
seems that speed of the application has taken a back seat to reliability.
Anyone remember when you were told not to make too many function calls
because of the overhead? That was if you wanted to make your app fast. That
was a LONG time ago let me tell ya.

>
> Mungo Henning
>
> P.S. My rules for global variables (having been bitten badly by the damn
> things)
> include using long unambiguous names and requiring that the name of the
> creator be left in a comment beside the global so that they could be
> shot
> later... ;-)
>

Now there's an idea. Hmm. Darn, we'd have to find the bugger to shoot him
though. He wisely made globals and then left. I have a feeling that if he'd
had to debug the thing or maintain it himself he would have been a bit more
conservative in his use of globals.

> I guess namespaces are the saviour for this problem, but it sure made
> life

I'm still learning the joys of namespaces. So far I've gotten to the point
where I'm not using the new style headers and qualifying things like
std::cout and the like. I haven't gotten into creating my own namespaces
just yet though.

> interesting in C when your boss decided to declare three variables in a
> header
> (which was
> #included in EVERY source file) whose type was 'int' and whose names
> were 'i',
> 'j'
> and 'k'... 'for' loops were never so interesting... :-)
>

You too!?! Man, this code I'm working with I couldn't believe he actually
made a global variable named x. X! Oh my head... I had one "programmer" (I
call them coders) tell me to just use the variable i. I said but I'm in a
different function and this function hasn't created that variable yet. He
said just use it. I did and it was and I screamed. Was this BASIC or
something? So I tracked down the variable. The creator of the code in his
infinite wisdom had initialized the variable in another C module as a global
variable and that module was included (Yes #include "file.c") at the top of
the one I was in..

Mungo Henning

unread,
Oct 17, 1998, 3:00:00 AM10/17/98
to
Kendall Beaman wrote:

> You too!?! Man, this code I'm working with I couldn't believe he actually
> made a global variable named x. X! Oh my head...

What's the problem with a variable called "x"? I suppose it depends on the
application ("x" being used as a coordinate etc) but having heard the reaction
of a tutor to a students non-working programme, I try and steer away from
non-obvious names (with the exception of simple loop variables... halo intact!)
The aforementioned student had a non-working program, so they took it to the
tutor for help... first variable was called "x", second was "xx", three guesses
to the third variable's name... :-)

Mungo

Kendall Beaman

unread,
Oct 17, 1998, 3:00:00 AM10/17/98
to
Mungo Henning wrote:

> Kendall Beaman wrote:
>
> > You too!?! Man, this code I'm working with I couldn't believe he
actually
> > made a global variable named x. X! Oh my head...
>
> What's the problem with a variable called "x"? I suppose it depends on
the
> application ("x" being used as a coordinate etc) but having heard the
reaction
> of a tutor to a students non-working programme, I try and steer away
from
> non-obvious names (with the exception of simple loop variables... halo
intact!)
> The aforementioned student had a non-working program, so they took it
to the
> tutor for help... first variable was called "x", second was "xx",
three guesses
> to the third variable's name... :-)
>
> Mungo

Nothing is really wrong with a variable called x. Problem is that many
programmers,
myself included, use x,y,z for our local counter variables in for loops.
I heard of
a study done once. It seems that depending on your own programming
background or
that of your teacher you either used x,y,z or i,j,k. I think Fortran
programmers
tended to use i,j,k. Not sure. But that's the main reason with creating
a global
variable called x. Now another reason I'd give is that it isn't
descriptive at all.
If you absolutely HAD to create a global variable I'd at least make it a
descriptive name. If its a coordinate then maybe XCoordinate or
something like
that.

All...@my-dejanews.com

unread,
Oct 20, 1998, 3:00:00 AM10/20/98
to
In article <3624EDB0...@sensor.com>,

Ron Natalie <r...@sensor.com> wrote:
> Unfortuantely, static is one of those much abused keywords
> in C++.
<
> Kendall Beaman wrote:
> > I wrote this little program and compiled it under VC++.
> >
> > #include <iostream>
> >
> > static int x;
> >
> > int main (void)
> > {
> >
> > std::cout << x << std::endl;
> >
> > return 0;
> > }
> >
> > The result was that it printed out a zero. Ok cool. But then I removed
> > the
> > static keyword and it still printed out zero. So now I'm curious. What
> > does
> > the standard for C/C++ actually say about this?
> >
> >
> Which is as it should be. Where you see a difference is inside
> a block:
>
> int main() {
> static int x;
> std::cout << x << std::endl;
> }
>
> will print a zero, where
>
> int main() {
> int x;
> std::cout << x << std::endl;
> }
>
> has undefined results.

That's part of the answer.

USES OF KEYWORD static
----------------------

1. For data inside a function or block, allocates a single instance
of that variable. This is useful for non-heap variables that must
outlive the lifetime of the function or block they are in, as
when the address of a character buffer is returned to the caller.
This is also useful for communication amongst various
instanciations of a recursive function (not that I'm advocating
that, mind you). There are still other uses, such as a "first
time" flag, or statistics for debugging, or maintaining function
state.

As you noted, such variables are always initialized. What you
didn't notice was *WHEN* they are initialized -- this happens
the very first time that the function or block is entered.
Granted, for integers initialized by a constant this is not an
issue, but consider:

int counter() { static int c = 0; return ++c; }
int counter2() { static int d = counter(); return ++d; }
int main() { counter(); counter(); counter2();
return counter()+counter2(); }

This returns 9. Can you see why?

I'm pretty sure that all of this is true in both C and C++.

2. For data at file scope, indicates data that is not visible in
other compilation units. That is:

// x.cpp
static int a = 4;

// y.cpp
static int a = 9;

The variable "a" in x.cpp is not the same variable as "a" in y.cpp.
Again, both variables are initialized at some point.

This is true in both C and C++. However, C++ has two superior
replacements. The first is given in #4 below; the second is even
better: nameless namespaces.

namespace {
int a = 4;
}

This variable "a" cannot be seen in any other translation unit.
Unlike it's "static" brother, it usually *can* be seen by debuggers
(but this is beyond the scope of a language spec).

3. For functions, indicates that the name is not external. For instance:
// x.cpp
// Contrived example, work with me!
static myNode*goNext(myNode*d) { return d->next; }

// y.cpp
static myNode*goNext(myNode*d) { return d ? d->next : nodeHead; }

These two declarations of goNext() do not conflict with each other
because each one is local to it's own translation unit.

You may notice that #3 is just a special case of #2 -- it refers to
function names instead of data names, but the effect is the same.
This works for both C and C++, although again C++ offers two
superior alternatives (class static and nameless namespaces).

4. For data inside a class, indicates a single-instance data item.
Such data exists in memory once, no matter how many instances of
the class are created.

5. For functions in a class, indicates a function that does not
operate on particular instanciations of the class. It is able to
access static class data, however.

--
All...@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Nate Lewis

unread,
Oct 20, 1998, 3:00:00 AM10/20/98
to
All...@my-dejanews.com wrote in message
<70gccf$a23$1...@nnrp1.dejanews.com>...

> int counter() { static int c = 0; return ++c; }
> int counter2() { static int d = counter(); return ++d; }
> int main() { counter(); counter(); counter2();
> return counter()+counter2(); }
>
> This returns 9. Can you see why?

Or 8; which of counter() and counter2() is executed first in that return
statement is undefined, is it not?

--
Nate Lewis, MCSD
nle...@mindspring.com

Andrei Alexandrescu

unread,
Oct 21, 1998, 3:00:00 AM10/21/98
to
All...@my-dejanews.com wrote in message <70gccf$a23$1...@nnrp1.dejanews.com>...
> As you noted, such variables are always initialized. What you
> didn't notice was *WHEN* they are initialized -- this happens
> the very first time that the function or block is entered.
> Granted, for integers initialized by a constant this is not an
> issue, but consider:
>
> int counter() { static int c = 0; return ++c; }
> int counter2() { static int d = counter(); return ++d; }
> int main() { counter(); counter(); counter2();
> return counter()+counter2(); }
>
> This returns 9. Can you see why?
>
> I'm pretty sure that all of this is true in both C and C++.


Sorry, that's wrong. First of all, C doesn't allow dynamically initialized
static variables. In C++, the rule differs for statically initialized and
dynamically initialized variables:

- statically initialized static variables are (just like in C) initialized
at compile time so you have absolutely no runtime overhead. This is the case
for:

void something() { static int c = 9; }

- dynamically initialized static variables are initialized at the first call
of the function. Before that first call, they are guaranteed to be zeroed.
This is the case for:

void something() { static int c = something_else(); }

Prior something() to be called, c will be zero. At the first call, it will
be initialized with the return value of something_else().

You may wonder, why's that rule that c will be zero? After all, it's not
even accessible prior to be constructed.
Actually, it is. Look at this:

void something() { static int c = something_else(c); }

Ooops! Here you can count on something_else() receving a zero. Interesting.
You can use this for VERY cool stuff.

Andrei

Nate Lewis

unread,
Oct 21, 1998, 3:00:00 AM10/21/98
to
Nate Lewis wrote in message <70i176$n35$1...@samsara0.mindspring.com>...

>All...@my-dejanews.com wrote in message
><70gccf$a23$1...@nnrp1.dejanews.com>...
>> int counter() { static int c = 0; return ++c; }
>> int counter2() { static int d = counter(); return ++d; }
>> int main() { counter(); counter(); counter2();
>> return counter()+counter2(); }
>>
>> This returns 9. Can you see why?
>
>Or 8; which of counter() and counter2() is executed first in that
return
>statement is undefined, is it not?


Never mind me, I'm just daft today, I got two corrections (thanks, guys)
before I knew the article had been approved. Trying to answer news
during breakfast is not recommended. :)

Sorry. :(

--
Nate Lewis, MCSD
nle...@mindspring.com

Andrei Alexandrescu

unread,
Oct 21, 1998, 3:00:00 AM10/21/98
to
Nate Lewis wrote in message <70i176$n35$1...@samsara0.mindspring.com>...
>Or 8; which of counter() and counter2() is executed first in that return
>statement is undefined, is it not?


Great point!

Andrei

All...@my-dejanews.com

unread,
Oct 24, 1998, 3:00:00 AM10/24/98
to
In article <362cb...@10.1.1.65>,

"Andrei Alexandrescu" <alexan...@micromodeling.com> wrote:
> All...@my-dejanews.com wrote in message <70gccf$a23$1...@nnrp1.dejanews.com>...
> > As you noted, such variables are always initialized. What you
> > didn't notice was *WHEN* they are initialized -- this happens
> > the very first time that the function or block is entered.
> > Granted, for integers initialized by a constant this is not an
> > issue, but consider:
> >
> > int counter() { static int c = 0; return ++c; }
> > int counter2() { static int d = counter(); return ++d; }
> > int main() { counter(); counter(); counter2();
> > return counter()+counter2(); }
> >
> > This returns 9. Can you see why?

Actually, as someone else pointed out, the return expression might call
counter2() before it calls counter(). So this could also return 8 in C++.

> > I'm pretty sure that all of this is true in both C and C++.
>
> Sorry, that's wrong. First of all, C doesn't allow dynamically initialized
> static variables.

Yes, this is true. I forgot that. So my example wouldn't even be
legal in C.

> In C++, the rule differs for statically initialized and
> dynamically initialized variables:
>
> - statically initialized static variables are (just like in C) initialized
> at compile time so you have absolutely no runtime overhead. This is the case
> for:
>
> void something() { static int c = 9; }
>
> - dynamically initialized static variables are initialized at the first call
> of the function. Before that first call, they are guaranteed to be zeroed.
> This is the case for:
>
> void something() { static int c = something_else(); }
>
> Prior something() to be called, c will be zero. At the first call, it will
> be initialized with the return value of something_else().

Well, very close.

3.6.2 Initialization of non-local objects [basic.start.init]

1 The storage for objects with static storage duration
(_basic.stc.static_) shall be zero-initialized (_dcl.init_) before any
other initialization takes place. Objects of POD types
(_basic.types_) with static storage duration initialized with constant
expressions (_expr.const_) shall be initialized before any dynamic
initialization takes place.

So it's not either/or, it's both. At least conceptually, the variable is
zero-initialized first, and then re-initialized on first access.

In reality, of course, the as-if rule allows a compiler to do just one
initialization, so long as it can prove that the result is the same as
if the 0 had been stored first. For objects of POD types with constant
expressions, this is trivial.

> You may wonder, why's that rule that c will be zero? After all, it's not
> even accessible prior to be constructed.
> Actually, it is. Look at this:
>
> void something() { static int c = something_else(c); }
>
> Ooops! Here you can count on something_else() receving a zero. Interesting.
> You can use this for VERY cool stuff.

Well, yes. But you can also use it to detect that global variables
have not yet been initialized. All global variables must be initialized
before main() is called, but that initialization can call constructors,
which can call other functions, and so on, with the result that in
general you can't be sure if main() has already been called, which
means you can't be sure that all globals are initialized. But you can
easily use a first-time-flag (or anything else where 0 means "not yet
initialized") and initialize on demand...

--
All...@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

Nate Lewis

unread,
Oct 25, 1998, 2:00:00 AM10/25/98
to
All...@my-dejanews.com wrote in message
<70ob4q$ssb$1...@nnrp1.dejanews.com>...

>> > int counter() { static int c = 0; return ++c; }
>> > int counter2() { static int d = counter(); return ++d; }
>> > int main() { counter(); counter(); counter2();
>> > return counter()+counter2(); }
>> >
>> > This returns 9. Can you see why?
>
>Actually, as someone else pointed out, the return expression might call
>counter2() before it calls counter(). So this could also return 8 in
C++.


That was me, and I was wrong; no part of that return expression has side
effects that might affect any other part. It could call counter2()
before it calls counter(), but it wouldn't matter. The second call to
counter2() wouldn't call counter(), since d was initialized earlier;
counter() will return 4 and counter2() will return 5 regardless of what
order they're called in.

--
Nate Lewis, MCSD
nle...@mindspring.com

[ Send an empty e-mail to c++-...@netlab.cs.rpi.edu for info ]

The BEAST(without the beauty)

unread,
Oct 26, 1998, 3:00:00 AM10/26/98
to
each static is only inicialized once, so:


int counter() { static int c = 0; return ++c; }
int counter2() { static int d = counter(); return ++d; }
int main()
{
counter();

// inicializes c with 0
// c <- 1
counter();
// c <- 2
counter2();

// it calls counter so c <- 3 also inicializes d with 3
// d <- 4
return
counter()
// c <- 4
+
counter2();
// d <- 5
}

// 4 + 5 = 9 amazing isnt it


-----------------------------------------------------------
(signature here)

The BEAST(without the beauty)

unread,
Oct 26, 1998, 3:00:00 AM10/26/98
to
On 21 Oct 1998, Andrei Alexandrescu wrote:

> Nate Lewis wrote in message <70i176$n35$1...@samsara0.mindspring.com>...
> >Or 8; which of counter() and counter2() is executed first in that
return
> >statement is undefined, is it not?
>
>
> Great point!
>
> Andrei
>

no its bad...

after the first call to 'counter2' the variable d is inicialized
on the next calls to the function it is only incremented...

see post before

----------------------------------------------------------------------
ASC THE BEAST

0 new messages