Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #36524 > unrolled thread

why do some writers declare and define variables separately

Started byyoodavid <odimegwudavid@yahoo.fr>
First post2013-09-18 16:42 -0500
Last post2013-10-03 21:15 +0200
Articles 20 on this page of 74 — 25 participants

Back to article view | Back to comp.lang.c


Contents

  why do some writers declare and define variables separately yoodavid <odimegwudavid@yahoo.fr> - 2013-09-18 16:42 -0500
    Re: why do some writers declare and define variables separately Fred K <fred.l.kleinschmidt@gmail.com> - 2013-09-18 14:52 -0700
    Re: why do some writers declare and define variables separately Eric Sosman <esosman@comcast-dot-net.invalid> - 2013-09-18 18:08 -0400
    Re: why do some writers declare and define variables separately T0xicCode <T0xic@co.de> - 2013-09-18 18:10 -0400
      Re: why do some writers declare and define variables separately Ken Brody <kenbrody@spamcop.net> - 2013-09-19 11:16 -0400
        Re: why do some writers declare and define variables separately T0xicCode <T0xic@co.de> - 2013-09-19 11:45 -0400
    Re: why do some writers declare and define variables separately Keith Thompson <kst-u@mib.org> - 2013-09-18 15:45 -0700
    Re: why do some writers declare and define variables separately Jens Schmidt <Jens.Schmidt-HH@gmx.de> - 2013-09-19 01:19 +0200
    Re: why do some writers declare and define variables separately Francis Glassborow <francis.glassborow@btinternet.com> - 2013-09-19 02:13 +0100
      Re: why do some writers declare and define variables separately Ben Bacarisse <ben.usenet@bsb.me.uk> - 2013-09-19 03:59 +0100
        Re: why do some writers declare and define variables separately Phil Carmody <thefatphil_demunged@yahoo.co.uk> - 2013-09-27 00:49 +0300
        Re: why do some writers declare and define variables separately Anand Hariharan <mailto.anand.hariharan@gmail.com> - 2013-10-03 15:41 -0700
          Re: why do some writers declare and define variables separately Ben Bacarisse <ben.usenet@bsb.me.uk> - 2013-10-04 00:42 +0100
      Re: why do some writers declare and define variables separately Eric Sosman <esosman@comcast-dot-net.invalid> - 2013-09-19 00:01 -0400
        Re: why do some writers declare and define variables separately David Brown <david@westcontrol.removethisbit.com> - 2013-09-19 10:17 +0200
        Re: why do some writers declare and define variables separately "osmium" <r124c4u102@comcast.net> - 2013-09-19 06:44 -0500
        Re: why do some writers declare and define variables separately Les Cargill <lcargill99@comcast.com> - 2013-09-19 08:00 -0500
          Re: why do some writers declare and define variables separately Noob <root@127.0.0.1> - 2013-09-19 15:12 +0200
          Re: why do some writers declare and define variables separately Keith Thompson <kst-u@mib.org> - 2013-09-19 08:31 -0700
            Re: why do some writers declare and define variables separately Eric Sosman <esosman@comcast-dot-net.invalid> - 2013-09-19 11:35 -0400
              Re: why do some writers declare and define variables separately Keith Thompson <kst-u@mib.org> - 2013-09-19 12:16 -0700
                Re: why do some writers declare and define variables separately Eric Sosman <esosman@comcast-dot-net.invalid> - 2013-09-19 15:32 -0400
                  Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-09-22 12:36 -0700
          Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-09-22 11:28 -0700
            Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-09-23 03:26 -0700
              Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-09-24 20:33 -0700
                Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-09-25 04:37 -0700
                  Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-22 21:23 -0700
                    Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-10-23 04:34 -0700
                  Re: why do some writers declare and define variables separately Ben Bacarisse <ben.usenet@bsb.me.uk> - 2013-10-23 16:02 +0100
                    Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-10-24 02:31 -0700
                      Re: why do some writers declare and define variables separately Ben Bacarisse <ben.usenet@bsb.me.uk> - 2013-10-24 12:27 +0100
                        Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-10-24 08:08 -0700
                Re: why do some writers declare and define variables separately Keith Thompson <kst-u@mib.org> - 2013-09-25 08:24 -0700
                  Re: why do some writers declare and define variables separately glen herrmannsfeldt <gah@ugcs.caltech.edu> - 2013-09-25 19:08 +0000
                  Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-22 00:22 -0700
                    Re: why do some writers declare and define variables separately Olle Villesen <noemail@replytogroup.org> - 2013-10-22 07:48 +0000
                      Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-23 18:13 -0700
                        Re: why do some writers declare and define variables separately glen herrmannsfeldt <gah@ugcs.caltech.edu> - 2013-10-24 03:12 +0000
                          Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-24 10:58 -0700
                    Re: why do some writers declare and define variables separately Martin Shobe <martin.shobe@yahoo.com> - 2013-10-22 08:55 -0500
                      Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-24 06:15 -0700
            Re: why do some writers declare and define variables separately Les Cargill <lcargill99@comcast.com> - 2013-09-25 17:37 -0500
              Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-10-22 01:15 -0700
      Re: why do some writers declare and define variables separately Tim Rentsch <txr@alumni.caltech.edu> - 2013-09-22 11:34 -0700
    Re: why do some writers declare and define variables separately gordonb.t5wsh@burditt.org (Gordon Burditt) - 2013-09-25 05:29 -0500
      Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-25 22:35 +1200
        Re: why do some writers declare and define variables separately David Brown <david@westcontrol.removethisbit.com> - 2013-09-25 13:02 +0200
        Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 08:39 -0400
          Re: why do some writers declare and define variables separately Keith Thompson <kst-u@mib.org> - 2013-09-25 08:23 -0700
          Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 08:06 +1200
            Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 16:38 -0400
              Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 09:17 +1200
                Re: why do some writers declare and define variables separately Öö Tiib <ootiib@hot.ee> - 2013-09-25 14:32 -0700
                  Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 09:50 +1200
                Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 09:55 +1200
                Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 18:50 -0400
                  Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 11:17 +1200
                    Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 21:26 -0400
                      Re: why do some writers declare and define variables separately Ian Collins <ian-news@hotmail.com> - 2013-09-26 13:50 +1200
        Re: why do some writers declare and define variables separately Noob <root@127.0.0.1> - 2013-09-25 15:55 +0200
          Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 10:03 -0400
            Re: why do some writers declare and define variables separately Phil Carmody <thefatphil_demunged@yahoo.co.uk> - 2013-09-27 01:29 +0300
        Re: why do some writers declare and define variables separately Phil Carmody <thefatphil_demunged@yahoo.co.uk> - 2013-09-27 01:20 +0300
      Re: why do some writers declare and define variables separately David Brown <david@westcontrol.removethisbit.com> - 2013-09-25 13:05 +0200
        Re: why do some writers declare and define variables separately Ben Bacarisse <ben.usenet@bsb.me.uk> - 2013-09-25 23:01 +0100
          Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-25 18:56 -0400
            Re: why do some writers declare and define variables separately David Brown <david@westcontrol.removethisbit.com> - 2013-09-26 09:10 +0200
              Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-26 07:31 -0400
                Re: why do some writers declare and define variables separately David Brown <david@westcontrol.removethisbit.com> - 2013-09-26 13:58 +0200
                  Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-09-26 09:12 -0400
    Re: why do some writers declare and define variables separately Michael Lenz <unrest@nullvector.org> - 2013-10-03 19:06 +0000
      Re: why do some writers declare and define variables separately James Kuyper <jameskuyper@verizon.net> - 2013-10-03 15:26 -0400
    Re: why do some writers declare and define variables separately Dag-Erling Smørgrav <des@des.no> - 2013-10-03 21:15 +0200

Page 1 of 4  [1] 2 3 4  Next page →


#36524 — why do some writers declare and define variables separately

Fromyoodavid <odimegwudavid@yahoo.fr>
Date2013-09-18 16:42 -0500
Subjectwhy do some writers declare and define variables separately
Message-ID<clcm-20130918-0002@plethora.net>
Can anyone tell me why some writers decide to declare and 
write definitions for variables separately, rather than 
together?

That is:
int definelater;
...
definelater = 0;

rather than:
int definelater = 0;

wouldn't the later reduce code lines? 
thanks. 
-- 
to authenticate is not to authorize. be responsible.
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.

[toc] | [next] | [standalone]


#36525

FromFred K <fred.l.kleinschmidt@gmail.com>
Date2013-09-18 14:52 -0700
Message-ID<02981a08-b893-4cf0-8f64-4f38207fb95a@googlegroups.com>
In reply to#36524
On Wednesday, September 18, 2013 2:42:10 PM UTC-7, yoodavid wrote:
> Can anyone tell me why some writers decide to declare and write definitions for variables separately, rather than together? That is: int definelater; ... definelater = 0; rather than: int definelater = 0; wouldn't the later reduce code lines? thanks. -- to authenticate is not to authorize. be responsible. -- comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must have an appropriate newsgroups line in your header for your mail to be seen, or the newsgroup name in square brackets in the subject line. Sorry.

This is really a style issue. Each person has different preferences; some come form historic use with other languages.

You may not know what value to initialize it to. For example:
   int xxx;
   if ( something ) {
      xxx = readValueFormFile(...);
   else if ( somethingElse ) {
      xxx = getValueFromDatabase(...);
   else {
      xxx = popDialogAndGetValue(...);
   else {
      return errorValue;
   }

-- 
Fred K

[toc] | [prev] | [next] | [standalone]


#36526

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2013-09-18 18:08 -0400
Message-ID<l1d89e$vr4$1@dont-email.me>
In reply to#36524
On 9/18/2013 5:42 PM, yoodavid wrote:
> Can anyone tell me why some writers decide to declare and
> write definitions for variables separately, rather than
> together?
>
> That is:
> int definelater;
> ...
> definelater = 0;
>
> rather than:
> int definelater = 0;
>
> wouldn't the later reduce code lines?

     Yes, and it has some other potential advantages as well.
However, "Old Time Original C As Our Forefathers Knew It" had
a restriction: All the declarations in a {}-enclosed block
had to precede all the executable statements.  This restriction
was removed by the 1999 edition of the C Standard, but (even
to this day!) some compilers have not yet caught up to 1999.
If you're writing code that might need to work with those
outdated compilers -- or if your habits were formed before
the restriction was lifted -- you'll group the declarations
at the start of each block.

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#36527

FromT0xicCode <T0xic@co.de>
Date2013-09-18 18:10 -0400
Message-ID<Dxp_t.59871$ei6.53255@fx08.am4>
In reply to#36524
On 13-09-18 05:42 PM, yoodavid wrote:
> Can anyone tell me why some writers decide to declare and
> write definitions for variables separately, rather than
> together?
>
> That is:
> int definelater;
> ...
> definelater = 0;
>
> rather than:
> int definelater = 0;
>
> wouldn't the later reduce code lines?
> thanks.
>

Readability is also an important factor. Having the lowest number of 
lines doesn't do much if no one (including you after you haven't touched 
it for a few weeks) can easily understand what the code does.

In any case, compilers nowadays are pretty smart, and I'm pretty sure 
that with the right options (-O3), they would optimize the separate 
calls into a single define and initialize.

[toc] | [prev] | [next] | [standalone]


#36541

FromKen Brody <kenbrody@spamcop.net>
Date2013-09-19 11:16 -0400
Message-ID<l1f4h9$617$1@dont-email.me>
In reply to#36527
On 9/18/2013 6:10 PM, T0xicCode wrote:
> On 13-09-18 05:42 PM, yoodavid wrote:
>> Can anyone tell me why some writers decide to declare and
>> write definitions for variables separately, rather than
>> together?
>>
>> That is:
>> int definelater;
>> ...
>> definelater = 0;
>>
>> rather than:
>> int definelater = 0;
[...]
> In any case, compilers nowadays are pretty smart, and I'm pretty sure that
> with the right options (-O3), they would optimize the separate calls into a
> single define and initialize.

I'm not sure what you are saying about optimizing, since there is nothing to 
"optimize" here.  The statement "int definelater;" generates no code(*).

(*) Okay, if "definelater" is the *only* variable in the function, then it 
make take some code to reserve space for the local variable.  However, that 
same code would be required for "int definelater=0;".

[toc] | [prev] | [next] | [standalone]


#36544

FromT0xicCode <T0xic@co.de>
Date2013-09-19 11:45 -0400
Message-ID<Q_E_t.1458$ey4.905@fx02.iad>
In reply to#36541
On 13-09-19 11:16 AM, Ken Brody wrote:
> (*) Okay, if "definelater" is the *only* variable in the function, then
> it make take some code to reserve space for the local variable.
> However, that same code would be required for "int definelater=0;".

I remember reading something on optimizing C code for embedded 
platforms, but I can't find it for the life of me.

-- 
--------
T0xicCode

[toc] | [prev] | [next] | [standalone]


#36529

FromKeith Thompson <kst-u@mib.org>
Date2013-09-18 15:45 -0700
Message-ID<lnzjr992ah.fsf@nuthaus.mib.org>
In reply to#36524
yoodavid <odimegwudavid@yahoo.fr> writes:
> Can anyone tell me why some writers decide to declare and 
> write definitions for variables separately, rather than 
> together?
>
> That is:
> int definelater;
> ...
> definelater = 0;
>
> rather than:
> int definelater = 0;
>
> wouldn't the later reduce code lines? 

Your terminology is a bit off.  This line:

    int definelater;

both *declares* and *defines* the variable.  (Roughly, declaring a
variable makes its name visible, and defining it allocate storage for
it.)  The "= 0", when it's part of the declaration is an *initializer*.
When written separately, "definelater = 0;" is an *assignment*.

Usually it's better, when possible, to use an initializer rather than a
separate assignment -- not because it saves lines of code, but because
it's clearer.

One case where a separate assignment is more appropriate is when you
don't know, at the point of the declaration, what value should be
assigned:

    int obj;
    if (some_condition) {
        obj = this_value;
    }
    else {
        obj = that_value;
    }

The ability to mix declarations and statements, introduced in C99, can
alleviate this in some cases, making it easier to move the declaration
to the point where you know how to initialize it:

    int x = some_value;
    int y;
    some_func(&y);
    int z = x + y;

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#36531

FromJens Schmidt <Jens.Schmidt-HH@gmx.de>
Date2013-09-19 01:19 +0200
Message-ID<b9uqnkF7dvbU1@mid.uni-berlin.de>
In reply to#36524
yoodavid wrote:

> Can anyone tell me why some writers decide to declare and 
> write definitions for variables separately, rather than 
> together?

Your code doesn't have any separate declaration. What is separate are
definition and initialisation. A declaration would be e.g. a line
  extern int definelater;
at the very begining.

As I can't read the mind of "some writers", here are some guesses:
Early versions of C didn't have the possibility to define variables
everywhere in a function. You had to first define or declare all names
used in the function and only then start with statements.
Complex types, i.e. struct and union types, are not always initializeable
inside the definition. So you have to initialize in separate statements.
Now the programmer initialiazes everything this way for consistency.
I'd categorize that as marginally valid at its time, but obsolete with
modern usage.

> wouldn't the later reduce code lines? 

Reduction of code lines a non-relevant argument nowadays. The most expensive
resource in computing is the programmer. So the criteria for coding style
are a) is it clearly visible from the source code, what the intention was
and b) is it improbable to introduce errors, especially later when changing
the code.
Actually the result is the same: initialize as soon after definition.
-- 
Greetings,
  Jens Schmidt

[toc] | [prev] | [next] | [standalone]


#36533

FromFrancis Glassborow <francis.glassborow@btinternet.com>
Date2013-09-19 02:13 +0100
Message-ID<uKqdnczlP_M30qfPnZ2dnUVZ8sWdnZ2d@bt.com>
In reply to#36524
On 18/09/2013 22:42, yoodavid wrote:
> Can anyone tell me why some writers decide to declare and
> write definitions for variables separately, rather than
> together?
>
> That is:
> int definelater;

That is a definition as well as a declaration. However the variable has 
not been initialised

> ...
> definelater = 0;
>
> rather than:
> int definelater = 0;

Well that is just an assignment.
>
> wouldn't the later reduce code lines?
> thanks.


Not always. Consider:

int foo (int test){
    int i;
    if (test > 0) i = test;
    else i = -test;
/+ rest of code */

}

Now it is possible to initialise i to test and then change the stored 
value as a result of the if statement. One thing to remember is that in 
classic C all variables had to be declared/defined before any other 
executable statements in a block of code. Sometimes it was simply not 
possible to know what the value would be so initialising it at the point 
of definition might be considered to be a waste of time.


Having said that, it is almost always bad code to leave a variable in an 
uninitialised state. It is a recipe for future problems.

Francis

[toc] | [prev] | [next] | [standalone]


#36534

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2013-09-19 03:59 +0100
Message-ID<0.883853d7096134397d30.20130919035920BST.8761txv7nb.fsf@bsb.me.uk>
In reply to#36533
Francis Glassborow <francis.glassborow@btinternet.com> writes:

> On 18/09/2013 22:42, yoodavid wrote:
>> Can anyone tell me why some writers decide to declare and
>> write definitions for variables separately, rather than
>> together?
>>
>> That is:
>> int definelater;
>
> That is a definition as well as a declaration. However the variable
> has not been initialised

A couple of minor points...  If that line is at file scope, it's a
"tentative definition" and, if nothing happens to change things, it will
behave as if there were an initialiser (of zero).

>> ...
>> definelater = 0;
>>
>> rather than:
>> int definelater = 0;
>
> Well that is just an assignment.

Technically, no.  It's covered by the rules for initialising rather than
for assigning.

<snip>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#36763

FromPhil Carmody <thefatphil_demunged@yahoo.co.uk>
Date2013-09-27 00:49 +0300
Message-ID<8738orntid.fsf@bazspaz.fatphil.org>
In reply to#36534
Ben Bacarisse <ben.usenet@bsb.me.uk> writes:

> Francis Glassborow <francis.glassborow@btinternet.com> writes:
> 
> > On 18/09/2013 22:42, yoodavid wrote:
> >> Can anyone tell me why some writers decide to declare and
> >> write definitions for variables separately, rather than
> >> together?
> >>
> >> That is:
> >> int definelater;
> >
> > That is a definition as well as a declaration. However the variable
> > has not been initialised
> 
> A couple of minor points...  If that line is at file scope, it's a
> "tentative definition" and, if nothing happens to change things, it will
> behave as if there were an initialiser (of zero).
> 
> >> ...
> >> definelater = 0;
> >>
> >> rather than:
> >> int definelater = 0;
> >
> > Well that is just an assignment.
> 
> Technically, no.  It's covered by the rules for initialising rather than
> for assigning.

One of you appears to be talking about one of the two things there
and the other appears to be talking about the other of the two things
there. Perhaps if you used terms like "the former" and "the latter"
then there might be less confusion as to what you're talking about,
and there'd be less violent agreement.

Phil
-- 
The list of trusted root authorities in your browser included the
United Arab Emirates-based Etisalat, which was caught secretly
uploading spyware onto 100,000 customers' BlackBerries.
http://www.wired.com/threatlevel/2009/07/blackberry-spies/

[toc] | [prev] | [next] | [standalone]


#36969

FromAnand Hariharan <mailto.anand.hariharan@gmail.com>
Date2013-10-03 15:41 -0700
Message-ID<34e9ede9-8bb5-4143-b839-bd4bf5910ed7@googlegroups.com>
In reply to#36534
On Wednesday, September 18, 2013 9:59:20 PM UTC-5, Ben Bacarisse wrote:
> Francis Glassborow <francis.glassborow@btinternet.com> writes:
> > On 18/09/2013 22:42, yoodavid wrote:
> >> Can anyone tell me why some writers decide to declare and
> >> write definitions for variables separately, rather than
> >> together?
> >>
> >> That is:
> >> int definelater;
> >
> > That is a definition as well as a declaration. However the variable
> > has not been initialised
> A couple of minor points...  If that line is at file scope, it's a
> "tentative definition" and, if nothing happens to change things, it will
> behave as if there were an initialiser (of zero).
> >> ...
> >> definelater = 0;
> >>
> >> rather than:
> >> int definelater = 0;
> >
> > Well that is just an assignment.
> Technically, no.  It's covered by the rules for initialising rather than
> for assigning.


By "rules", I assume you are referring to syntactic constructs such as initializer lists?

In C, what are the semantic differences between initialisation and assignment?

- Anand

PS: I've tried to format my post as best as I can.  Sorry in advance if Google messes it up.

[toc] | [prev] | [next] | [standalone]


#36970

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2013-10-04 00:42 +0100
Message-ID<0.238d27023b5e077a5525.20131004004229BST.87mwmpkjkq.fsf@bsb.me.uk>
In reply to#36969
Anand Hariharan <mailto.anand.hariharan@gmail.com> writes:

> On Wednesday, September 18, 2013 9:59:20 PM UTC-5, Ben Bacarisse wrote:
>> Francis Glassborow <francis.glassborow@btinternet.com> writes:
>> > On 18/09/2013 22:42, yoodavid wrote:
>> >> Can anyone tell me why some writers decide to declare and
>> >> write definitions for variables separately, rather than
>> >> together?
>> >>
>> >> That is:
>> >> int definelater;
>> >
>> > That is a definition as well as a declaration. However the variable
>> > has not been initialised
>> A couple of minor points...  If that line is at file scope, it's a
>> "tentative definition" and, if nothing happens to change things, it will
>> behave as if there were an initialiser (of zero).
>> >> ...
>> >> definelater = 0;
>> >>
>> >> rather than:
>> >> int definelater = 0;
>> >
>> > Well that is just an assignment.
>> Technically, no.  It's covered by the rules for initialising rather than
>> for assigning.
>
> By "rules", I assume you are referring to syntactic constructs such as
> initializer lists?

Yes, but I meant all the rules -- semantic ones as well.

> In C, what are the semantic differences between initialisation and
> assignment?

For variables with simple scalar types, at block scope, in modern C, the
rules are very similar.  The only difference of note is that you can
initialise a const scalar, but you can't assign to one.

If the object is not a simple scalar, is at file scope, or you are using
old ANSI C, the differences start to multiply.  I wouldn't like to try
to list them all.

<snip>
> PS: I've tried to format my post as best as I can.  Sorry in advance
> if Google messes it up.

No, you seemed to have tamed the beast.  Did you have to do lots of hand
editing?

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#36535

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2013-09-19 00:01 -0400
Message-ID<l1dsv3$rhi$1@dont-email.me>
In reply to#36533
On 9/18/2013 9:13 PM, Francis Glassborow wrote:
> [...]
> One thing to remember is that in
> classic C all variables had to be declared/defined before any other
> executable statements in a block of code. Sometimes it was simply not
> possible to know what the value would be so initialising it at the point
> of definition might be considered to be a waste of time.
>
> Having said that, it is almost always bad code to leave a variable in an
> uninitialised state. It is a recipe for future problems.

     In modern "declare it whenever you like" C, I'd agree:
It is almost always better to postpone defining a variable
until you've got a reasonable initialization value.  However,
if one must define earlier I feel it is usually *not* a good
idea to fabricate an initializer out of thin air.  The common
advice "Initialize all pointer variables to NULL" is, I think,
a particularly bad example of bad practice.

     That's not to say it was always a bad practice.  A quarter
century ago compilers ran on sluggish systems in cramped memory
spaces; the basic job of translating the source code took all
the resources at their disposal and there was little left over
for dataflow analysis.  If you wrote

	char *evenOrOdd(int x) {
	    char *p;
	    switch (x % 2) {
	        case 0: p = "even"; break;
	        case 1: p = "odd"; break;
	    }
	    return p;
	}

... few old-time compilers would warn you that `p' might be
uninitialized in the `return' statement (because `x % 2' could
be -1).  In those days, writing

	char *evenOrOdd(int x) {
	    char *p = NULL;
	    switch (x % 2) {
	        case 0: p = "even"; break;
	        case 1: p = "odd"; break;
	    }
	    return p;
	}

... could be justified because it would likely give a reproducible
failure, easier to track down and solve than a Heisenbug.

     But that was a quarter century ago, when machines with a few
tens of megabytes ran at a few tens of megahertz.  That was back
in the days when the `register' keyword sometimes made sense.  Do
you still use `register', or do you rely on the compiler's more
thorough code analysis?  If the latter, why try to defeat that
same analysis when it comes to possibly uninitialized variables?

     Here's what I mean by the "defeat" remark:  With today's
compilers the first version of evenOrOdd() will almost certainly
elicit a diagnostic, and your attention will be drawn immediately
to the faulty code.  But the second will almost certainly *not*
draw a complaint, because the compiler can see that the variable
*is* initialized -- to a garbage value, but the compiler doesn't
know NULL is garbage.  Instead of detecting the bug at compile
time you detect it in testing (if you're lucky) or in deployment
(if less than lucky) or on final approach to Mars.  The safeguard
that long ago improved the bug from "awful" to merely "bad" now
prevents further improvement to "averted."  It's a stratagem that
refuses the compiler's offer of help -- and if you're like me,
you shouldn't refuse help.

     Don't just initialize variables for initialization's sake.
It's a superstition both outmoded and harmful.

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#36536

FromDavid Brown <david@westcontrol.removethisbit.com>
Date2013-09-19 10:17 +0200
Message-ID<R5-dnfN8la9jL6fPnZ2dnUVZ7tCdnZ2d@lyse.net>
In reply to#36535
On 19/09/13 06:01, Eric Sosman wrote:
> On 9/18/2013 9:13 PM, Francis Glassborow wrote:
>> [...]
>> One thing to remember is that in
>> classic C all variables had to be declared/defined before any other
>> executable statements in a block of code. Sometimes it was simply not
>> possible to know what the value would be so initialising it at the point
>> of definition might be considered to be a waste of time.
>>
>> Having said that, it is almost always bad code to leave a variable in an
>> uninitialised state. It is a recipe for future problems.
> 
>     In modern "declare it whenever you like" C, I'd agree:
> It is almost always better to postpone defining a variable
> until you've got a reasonable initialization value.  However,
> if one must define earlier I feel it is usually *not* a good
> idea to fabricate an initializer out of thin air.  The common
> advice "Initialize all pointer variables to NULL" is, I think,
> a particularly bad example of bad practice.
> 
>     That's not to say it was always a bad practice.  A quarter
> century ago compilers ran on sluggish systems in cramped memory
> spaces; the basic job of translating the source code took all
> the resources at their disposal and there was little left over
> for dataflow analysis.  If you wrote
> 
>     char *evenOrOdd(int x) {
>         char *p;
>         switch (x % 2) {
>             case 0: p = "even"; break;
>             case 1: p = "odd"; break;
>         }
>         return p;
>     }
> 
> ... few old-time compilers would warn you that `p' might be
> uninitialized in the `return' statement (because `x % 2' could
> be -1).  In those days, writing
> 
>     char *evenOrOdd(int x) {
>         char *p = NULL;
>         switch (x % 2) {
>             case 0: p = "even"; break;
>             case 1: p = "odd"; break;
>         }
>         return p;
>     }
> 
> ... could be justified because it would likely give a reproducible
> failure, easier to track down and solve than a Heisenbug.
> 
>     But that was a quarter century ago, when machines with a few
> tens of megabytes ran at a few tens of megahertz.  That was back
> in the days when the `register' keyword sometimes made sense.  Do
> you still use `register', or do you rely on the compiler's more
> thorough code analysis?  If the latter, why try to defeat that
> same analysis when it comes to possibly uninitialized variables?
> 
>     Here's what I mean by the "defeat" remark:  With today's
> compilers the first version of evenOrOdd() will almost certainly
> elicit a diagnostic, and your attention will be drawn immediately
> to the faulty code.  But the second will almost certainly *not*
> draw a complaint, because the compiler can see that the variable
> *is* initialized -- to a garbage value, but the compiler doesn't
> know NULL is garbage.  Instead of detecting the bug at compile
> time you detect it in testing (if you're lucky) or in deployment
> (if less than lucky) or on final approach to Mars.  The safeguard
> that long ago improved the bug from "awful" to merely "bad" now
> prevents further improvement to "averted."  It's a stratagem that
> refuses the compiler's offer of help -- and if you're like me,
> you shouldn't refuse help.
> 
>     Don't just initialize variables for initialization's sake.
> It's a superstition both outmoded and harmful.
> 

This is all true - but it depends on the user knowing how to use their
compiler properly.  I don't know what proportion of programmers don't
enable diagnostic warnings when building (or who ignore "mere warnings"
if they are enabled), but I believe it is very high.

[toc] | [prev] | [next] | [standalone]


#36538

From"osmium" <r124c4u102@comcast.net>
Date2013-09-19 06:44 -0500
Message-ID<ba06dfFfpb9U1@mid.individual.net>
In reply to#36535
"Eric Sosman" wrote:

>     Don't just initialize variables for initialization's sake.
> It's a superstition both outmoded and harmful.

Amen! 

[toc] | [prev] | [next] | [standalone]


#36539

FromLes Cargill <lcargill99@comcast.com>
Date2013-09-19 08:00 -0500
Message-ID<l1esb7$g9m$1@dont-email.me>
In reply to#36535
Eric Sosman wrote:
> On 9/18/2013 9:13 PM, Francis Glassborow wrote:
>> [...]
>> One thing to remember is that in
>> classic C all variables had to be declared/defined before any other
>> executable statements in a block of code. Sometimes it was simply not
>> possible to know what the value would be so initialising it at the point
>> of definition might be considered to be a waste of time.
>>
>> Having said that, it is almost always bad code to leave a variable in an
>> uninitialised state. It is a recipe for future problems.
>
>      In modern "declare it whenever you like" C, I'd agree:
> It is almost always better to postpone defining a variable
> until you've got a reasonable initialization value.  However,
> if one must define earlier I feel it is usually *not* a good
> idea to fabricate an initializer out of thin air.  The common
> advice "Initialize all pointer variables to NULL" is, I think,
> a particularly bad example of bad practice.
>

IMO, it goes back to many architectures trapping on dereferencing a NULL
pointer. It was a way of adding "terminating resistors" to code;
obviating Heisenbugs.

>      That's not to say it was always a bad practice.  A quarter
> century ago compilers ran on sluggish systems in cramped memory
> spaces; the basic job of translating the source code took all
> the resources at their disposal and there was little left over
> for dataflow analysis.  If you wrote
>
>      char *evenOrOdd(int x) {
>          char *p;
>          switch (x % 2) {
>              case 0: p = "even"; break;
>              case 1: p = "odd"; break;
>          }
>          return p;
>      }
>
> ... few old-time compilers would warn you that `p' might be
> uninitialized in the `return' statement (because `x % 2' could
> be -1).  In those days, writing
>
>      char *evenOrOdd(int x) {
>          char *p = NULL;
>          switch (x % 2) {
>              case 0: p = "even"; break;
>              case 1: p = "odd"; break;
>          }
>          return p;
>      }
>
> ... could be justified because it would likely give a reproducible
> failure, easier to track down and solve than a Heisenbug.
>

I would use this:

char *p = ( ( x % 2 ) == 0 ) ? "even" : "odd" ;

or

const char * const mInit[] = { "even", "odd" } ;

char *p = (char *)mInit[(x % 2)];

The point is to have a ... violently enforced
constraint on p that is completely invariant, no matter what.

That's more likely to be acceptable no matter the toolchain, unless
you're in a really old compiler.

If you need logic more complex than that, write an initializer
routine.

>      But that was a quarter century ago, when machines with a few
> tens of megabytes ran at a few tens of megahertz.  That was back
> in the days when the `register' keyword sometimes made sense.  Do
> you still use `register', or do you rely on the compiler's more
> thorough code analysis?  If the latter, why try to defeat that
> same analysis when it comes to possibly uninitialized variables?
>
>      Here's what I mean by the "defeat" remark:  With today's
> compilers the first version of evenOrOdd() will almost certainly
> elicit a diagnostic, and your attention will be drawn immediately
> to the faulty code.  But the second will almost certainly *not*
> draw a complaint, because the compiler can see that the variable
> *is* initialized -- to a garbage value, but the compiler doesn't
> know NULL is garbage.  Instead of detecting the bug at compile
> time you detect it in testing (if you're lucky) or in deployment
> (if less than lucky) or on final approach to Mars.  The safeguard
> that long ago improved the bug from "awful" to merely "bad" now
> prevents further improvement to "averted."  It's a stratagem that
> refuses the compiler's offer of help -- and if you're like me,
> you shouldn't refuse help.
>
>      Don't just initialize variables for initialization's sake.
> It's a superstition both outmoded and harmful.
>


I rather doubt that. One of the more useful things from OO is
RAII - Resource Allocation Is Initialization. There are at least
analogs in non-OO; this is one.

You may well be saying the same thing and I missed it; your point is 
unclear to me.

--
Les Cargill

[toc] | [prev] | [next] | [standalone]


#36540

FromNoob <root@127.0.0.1>
Date2013-09-19 15:12 +0200
Message-ID<l1et6n$lbn$3@dont-email.me>
In reply to#36539
Les Cargill wrote:

> Eric Sosman wrote:
> 
>> [...] `p' might be uninitialized (because `x % 2' could be -1).
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^

> I would use this:
> [...]
> const char * const mInit[] = { "even", "odd" } ;
> char *p = (char *)mInit[(x % 2)];

And panic ensues when x % 2 equals -1?

[toc] | [prev] | [next] | [standalone]


#36542

FromKeith Thompson <kst-u@mib.org>
Date2013-09-19 08:31 -0700
Message-ID<lnob7o96ab.fsf@nuthaus.mib.org>
In reply to#36539
Les Cargill <lcargill99@comcast.com> writes:
[...]
> I would use this:
>
> char *p = ( ( x % 2 ) == 0 ) ? "even" : "odd" ;
>
> or
>
> const char * const mInit[] = { "even", "odd" } ;
>
> char *p = (char *)mInit[(x % 2)];
>
> The point is to have a ... violently enforced
> constraint on p that is completely invariant, no matter what.

That last one can still have undefined behavior when x % 2 == -1.
Following the pattern of your first example, you could write it as:

    char *p = (char *)mInit[(x % 2) == 0];

And since p is expected to point to a string literal, it should be const
(the same criticism applies to Eric's code upthread), which neatly
avoids any need for casts.  I might write your two examples as:

    const char *p = x % 2 == 0 ? "even" : "odd";

and

    const char *const mInit[] = { "even", "odd" };
    const char *p = mInit[x % 2 == 0];

(probably the former, since I find it clearer).

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#36543

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2013-09-19 11:35 -0400
Message-ID<l1f5j3$c06$1@dont-email.me>
In reply to#36542
On 9/19/2013 11:31 AM, Keith Thompson wrote:
> Les Cargill <lcargill99@comcast.com> writes:
> [...]
>> I would use this:
>>
>> char *p = ( ( x % 2 ) == 0 ) ? "even" : "odd" ;
>>
>> or
>>
>> const char * const mInit[] = { "even", "odd" } ;
>>
>> char *p = (char *)mInit[(x % 2)];
>>
>> The point is to have a ... violently enforced
>> constraint on p that is completely invariant, no matter what.
>
> That last one can still have undefined behavior when x % 2 == -1.
> Following the pattern of your first example, you could write it as:
>
>      char *p = (char *)mInit[(x % 2) == 0];

     ... producing "odd" when x is even ...

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


Page 1 of 4  [1] 2 3 4  Next page →

Back to top | Article view | comp.lang.c


csiph-web