Stylistic questions on UNIX C coding.

  • Follow


Hi,

I've a few questions concerning style when programming C on UNIX systems. I 
don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15 years, I'm 
finding it hard to get used to DEFINES in all capitals. Is it really frowned on 
not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.


2. My personal variable and function naming style is camel case, with variable 
names beginning with a lower case char and function names not. Is that 
acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);


3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach 
120 chars I start thinking this might not look great in someone else's editor.


4. Does anyone care where the pointer * is? I prefer keeping to next to the 
type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;


5. On a slightly different note, I've been handling my error messages by using 
#define string constants in a header file. I saw some code which did this and it 
looked good to me. Is that standard practise, if not what is?

EG. #define ErrorDirNotFound "The directory was not found."


There are so many style guides out there, most of them say contradictory things 
at one point or another. What do the pros do?

Finally, before someone points this out... I know if I'm coding for myself, and 
not following somebody else's stylistic requirements, I can do whatever I want. 
However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

Thanks and regards, etc.
0
Reply postermatt (37) 2/24/2010 6:35:06 PM

On Feb 24, 1:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:
> Hi,
>
> I've a few questions concerning style when programming C on UNIX systems.=
 I
> don't want to look like an amateur. :)
>
> 1. Having been programming in higher level languages for the last 15 year=
s, I'm
> finding it hard to get used to DEFINES in all capitals. Is it really frow=
ned on
> not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

All caps is merely a convention so that macros are easier to see. If
you don't want to follow that convention, feel free. Though keep in
mind that conventions are there for a reason. The preprocessor has
proven troublesome enough over the years to warrant having macros
stand out a bit. ;-)

> 2. My personal variable and function naming style is camel case, with var=
iable
> names beginning with a lower case char and function names not. Is that
> acceptable, if not what is?
>
> EG:
> Variables: int numFiles =3D 0;
> Functions: int CountNumFilesInDir(char* path);

That's fine. I see that style often.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I=
 reach
> 120 chars I start thinking this might not look great in someone else's ed=
itor.

I try to keep each line under 100 characters (80 if possible). It's
less about monitor size than it is about easily reading my code at a
glance.

> 4. Does anyone care where the pointer * is? I prefer keeping to next to t=
he
> type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;

Just make sure you're consistent and nobody will care. :-)

> 5. On a slightly different note, I've been handling my error messages by =
using
> #define string constants in a header file. I saw some code which did this=
 and it
> looked good to me. Is that standard practise, if not what is?
>
> EG. #define ErrorDirNotFound "The directory was not found."

That's acceptable. Though keep in mind that in the age of
internationalization and localization, hard coding string literals
makes your code harder to port to other spoken languages.

> There are so many style guides out there, most of them say contradictory =
things
> at one point or another. What do the pros do?

The pros are just as contradictory as the style guides. Pick a style
you like and run with it, with the caveat that over time your tastes
(and as a result, your style) will evolve.

> Finally, before someone points this out... I know if I'm coding for mysel=
f, and
> not following somebody else's stylistic requirements, I can do whatever I=
 want.
> However I'd like my code to be 'acceptable looking' to the wider UNIX C c=
ommunity.

You can make bad code look pretty and it's still bad code. But in my
experience, good code has never looked ugly. Good aesthetics seems to
come naturally if you focus on writing the best code possible.
0
Reply happyfrosty (97) 2/24/2010 7:10:21 PM


On Feb 24, 11:10=A0am, Julienne Walker <happyfro...@hotmail.com> wrote:
> On Feb 24, 1:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>
> > Hi,
>
> > I've a few questions concerning style when programming C on UNIX system=
s. I
> > don't want to look like an amateur. :)
>
> > 1. Having been programming in higher level languages for the last 15 ye=
ars, I'm
> > finding it hard to get used to DEFINES in all capitals. Is it really fr=
owned on
> > not to do so? Is CamelCase acceptable?
>
> > EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.
>
> All caps is merely a convention so that macros are easier to see. If
> you don't want to follow that convention, feel free. Though keep in
> mind that conventions are there for a reason. The preprocessor has
> proven troublesome enough over the years to warrant having macros
> stand out a bit. ;-)
>
> > 2. My personal variable and function naming style is camel case, with v=
ariable
> > names beginning with a lower case char and function names not. Is that
> > acceptable, if not what is?
>
> > EG:
> > Variables: int numFiles =3D 0;
> > Functions: int CountNumFilesInDir(char* path);
>
> That's fine. I see that style often.
>
> > 3. Is there an accepted maximum line length? I've got a 24" monitor, if=
 I reach
> > 120 chars I start thinking this might not look great in someone else's =
editor.
>
> I try to keep each line under 100 characters (80 if possible). It's
> less about monitor size than it is about easily reading my code at a
> glance.
>
> > 4. Does anyone care where the pointer * is? I prefer keeping to next to=
 the
> > type, rather than next to the variable name.
>
> > EG. I like: char* firstName; and not so much: char *firstName;
>
> Just make sure you're consistent and nobody will care. :-)

Except that it is very error-prone to do so.

In C, the asterisk is associated with the variable name, not the type
specifier.
I've seen this so many times:

char*  x, y;

Here, x a pointer to char, but y is a char.

Much clearer to show what you really intended:

char *x, *y;   /* Both pointers */
 or
char *x, y;    /* One a pointer, one not */

>(snip)

--
Fred K
0
Reply fred.l.kleinschmidt (236) 2/24/2010 7:21:40 PM

On 24 Feb, 18:35, Poster Matt <postermatt@no_spam_for_me.org> wrote:
> Hi,
>
> I've a few questions concerning style when programming C on UNIX systems. I
> don't want to look like an amateur. :)

As a fellow amateur in C....

> 1. Having been programming in higher level languages for the last 15 years, I'm
> finding it hard to get used to DEFINES in all capitals. Is it really frowned on
> not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

While I use them I don't like all caps for #defined values for two
reasons

1) #defined values don't seem to me too far removed from global
parameters. Indeed if we change them to parameters in a function call
they lose upper case status. The two uses are similar. To my mind the
format of the names should also be similar.

2) I'd prefer to reserve all caps for macros. Then they serve as a
warning that parameters are not guaranteed to be evaluated exactly
once.

Many libraries use all caps for their constants.

You could also define constants in enums rather than in #defines.

>
> 2. My personal variable and function naming style is camel case, with variable
> names beginning with a lower case char and function names not. Is that
> acceptable, if not what is?

You'll probably get advised to stick to whatever coding standards your
project team members use. Also, when changing someone else's code,
stick to the standards used therein. For your own projects you could
use

  first_name
  firstname
  FirstName
  firstName

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
> 120 chars I start thinking this might not look great in someone else's editor.

Again, use existing coding standards if there are any. My monitor is
also wide but I prefer to keep to 80-columns because you never know
what size monitor the code will subsequently be edited on.

>
> 4. Does anyone care where the pointer * is? I prefer keeping to next to the
> type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;

It's normally as the latter due to

 char* FirstName, ch, *p;
 char *FirstName, ch, *p;

Regardless of which form is used I think only ch will be a char
variable - i.e. "char*" can be misleading. The other variables will be
pointers. Someone will correct me if I'm wrong. Though you are right
in principle, C does not cleanly segregate type and name. For example

  int func(int);

This declares the name func but the type information is scattered all
over such declarations.

> 5. On a slightly different note, I've been handling my error messages by using
> #define string constants in a header file. I saw some code which did this and it
> looked good to me. Is that standard practise, if not what is?
>
> EG. #define ErrorDirNotFound "The directory was not found."

That's much better than sprinkling messages throughout the code. If
followed consistently it makes clear what messages the code can issue.
Apart from clarity that would help if you ever want to release your
code in another human language. There are better ways with more
mechanism.

You may need a way to include variable values in your messages.

>
> There are so many style guides out there, most of them say contradictory things
> at one point or another. What do the pros do?
>
> Finally, before someone points this out... I know if I'm coding for myself, and
> not following somebody else's stylistic requirements, I can do whatever I want.
> However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

Check some examples: K&R2, C Unleashed, books by Douglas Comer, the
Linux source etc. Also there is a FAQ entry for style issues:

  http://c-faq.com/style/index.html

James
0
Reply james.harris.1 (384) 2/24/2010 7:29:01 PM

On February 24, 2010 13:35, in comp.lang.c, postermatt@no_spam_for_me.org
wrote:

> Hi,
> 
> I've a few questions concerning style when programming C on UNIX systems.
> I don't want to look like an amateur. :)
> 
> 1. Having been programming in higher level languages for the last 15
> years, I'm finding it hard to get used to DEFINES in all capitals. Is it
> really frowned on not to do so? Is CamelCase acceptable?
> 
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

CamelCase is acceptable, with the caveat that the programmer (you, or
whomever reads your code) should be able to distinguish the difference
between a macro and a variable.

> 2. My personal variable and function naming style is camel case, with
> variable names beginning with a lower case char and function names not. Is
> that acceptable, if not what is?
> 
> EG:
> Variables: int numFiles = 0;
> Functions: int CountNumFilesInDir(char* path);

Again, CamelCase is acceptable.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I
> reach 120 chars I start thinking this might not look great in someone
> else's editor.

Somewhere around 80 characters per line is the norm. That facilitates both
on-screen review and editing as well as printing and emailing of code.


> 4. Does anyone care where the pointer * is? I prefer keeping to next to
> the type, rather than next to the variable name.
> 
> EG. I like: char* firstName; and not so much: char *firstName;

That's acceptable, but prone to error.
Given
  char* firstName lastName;
what is the type of <lastName>?

If you read the declaration and answered that <lastName> is of char* type,
then you would be wrong. The language groups type modifiers to the defined
object, and not to the base type. Visually grouping the modifiers contrary
to how the language groups them can lead to programmer mis-interpretation
and error.
 
> 5. On a slightly different note, I've been handling my error messages by
> using
> #define string constants in a header file. I saw some code which did this
> #and it
> looked good to me. Is that standard practise, if not what is?
> 
> EG. #define ErrorDirNotFound "The directory was not found."

Most development groups I've worked with would find that practice
acceptable.

> There are so many style guides out there, most of them say contradictory
> things at one point or another. What do the pros do?

Usually, the pros do what the other pros that they are working with do.
Computer languages are a convenience to the /programmer/, not to the
computer. The rules (both at a language level, and at a developer level)
are set to make it easy for a programmer to write code, and for other
programmers to read (and often rewrite) it. So long as you apply your style
rules consistently (so that there are no unexpected deviations), things
should work out.

> Finally, before someone points this out... I know if I'm coding for
> myself, and not following somebody else's stylistic requirements, I can do
> whatever I want. However I'd like my code to be 'acceptable looking' to
> the wider UNIX C community.

/Which/ "UNIX C community"? Some communities have their own coding styles
("the one true style", or the K&R style, or the "Linux Kernel stye", for
instance), and no one set of rules will make your code acceptable to all of
the communities out there.

The best I can give you is to
a) be consistant, and
b) be simple
in your coding. Don't do the unexpected; once you've established a pattern,
stick with it until there is good reason to change. Document the change
ahead of time. Don't over-complicate things. The point is to make your code
easy to read and understand at the /human/ level.

> Thanks and regards, etc.

-- 
Lew Pitcher
Master Codewright & JOAT-in-training   | Registered Linux User #112576
Me: http://pitcher.digitalfreehold.ca/ | Just Linux: http://justlinux.ca/
----------      Slackware - Because I know what I'm doing.         ------


0
Reply lpitcher2 (869) 2/24/2010 7:29:22 PM

On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:
> 1. Having been programming in higher level languages for the last 15 years, I'm 
> finding it hard to get used to DEFINES in all capitals. Is it really frowned on 
> not to do so? Is CamelCase acceptable?

It'll work, but people will find it surprising.  All-caps as a warning that
something is a macro or other manifest constant is pretty canonical.

But you'd normally spell that one "MAX_FILES".

> 2. My personal variable and function naming style is camel case, with variable 
> names beginning with a lower case char and function names not. Is that 
> acceptable, if not what is?

I dislike it, anyway.  Convention is words_with_underscores().

> EG:
> Variables: int numFiles = 0;
> Functions: int CountNumFilesInDir(char* path);

Also, "Num" doesn't need to be there.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach 
> 120 chars I start thinking this might not look great in someone else's editor.

80ish is preferred.  Lines exceeding 80 will generally not be accepted by a
lot of projects unless there's a VERY good reason.

> 4. Does anyone care where the pointer * is? I prefer keeping to next to the 
> type, rather than next to the variable name.

> EG. I like: char* firstName; and not so much: char *firstName;

You are wrong.

I mean, sure, it compiles, but consider:

	char* x, y;

By contrast:
	char *x, y;
makes it clear that you are aware that the * modifies the variable, not the
type.

> 5. On a slightly different note, I've been handling my error messages by using 
> #define string constants in a header file. I saw some code which did this and it 
> looked good to me. Is that standard practise, if not what is?

> EG. #define ErrorDirNotFound "The directory was not found."

No.  Look into gettext() if you need to do this, or just put them in
literally.

> There are so many style guides out there, most of them say contradictory things 
> at one point or another. What do the pros do?

I use the Linux kernel style guide and/or the BSD style guide, which are
basically compatible.  Ignore the GNU coding standards, they're awful.

> Finally, before someone points this out... I know if I'm coding for myself, and 
> not following somebody else's stylistic requirements, I can do whatever I want. 
> However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

It's a good effort.  I do have to say, though... It's odd that you've managed
a complete sweep of, for every stylistic decision described above, picking
the opposite of the general convention in the UNIX world.  Where did you pick
up these preferences?

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 2/24/2010 7:32:35 PM

On Wed, 24 Feb 2010 11:10:21 -0800 (PST), Julienne Walker
<happyfrosty@hotmail.com> wrote:

>On Feb 24, 1:35�pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>> Hi,
>>
>> I've a few questions concerning style when programming C on UNIX systems. I
>> don't want to look like an amateur. :)

>> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
>> 120 chars I start thinking this might not look great in someone else's editor.
>
>I try to keep each line under 100 characters (80 if possible). It's
>less about monitor size than it is about easily reading my code at a
>glance.

Typographers, who study this thing with the fervor that programmers
bring to brace styles, would tend to agree. There are always reasonable
exceptions but a line length that's 70-80 characters (monospaced) seems
to be a sweet spot for comprehension.

>> 4. Does anyone care where the pointer * is? I prefer keeping to next to the
>> type, rather than next to the variable name.
>>
>> EG. I like: char* firstName; and not so much: char *firstName;
>
>Just make sure you're consistent and nobody will care. :-)

Except there's the danger in having one's thoughts focused elsewhere
when adding the next piece, and getting

  char* firstName, lastName;

-- 
Rich Webb     Norfolk, VA
0
Reply bbew.ar (758) 2/24/2010 7:35:21 PM

On Feb 24, 2:21=A0pm, Fred <fred.l.kleinschm...@boeing.com> wrote:
> On Feb 24, 11:10=A0am, Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Feb 24, 1:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote=
:
>
> > > 4. Does anyone care where the pointer * is? I prefer keeping to next =
to the
> > > type, rather than next to the variable name.
>
> > > EG. I like: char* firstName; and not so much: char *firstName;
>
> > Just make sure you're consistent and nobody will care. :-)
>
> Except that it is very error-prone to do so.

It's only error prone if you have multiple variables in a declaration
statement (which the OP's example did not). That itself is often
viewed as an unsafe practice.
0
Reply happyfrosty (97) 2/24/2010 7:42:48 PM

On 2/24/2010 1:35 PM, Poster Matt wrote:
> Hi,
>
> I've a few questions concerning style when programming C on UNIX
> systems. I don't want to look like an amateur. :)
>
> 1. Having been programming in higher level languages for the last 15
> years, I'm finding it hard to get used to DEFINES in all capitals. Is it
> really frowned on not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

     All-caps is one of those conventions that's widely adopted,
although there's no inherent linguisic necessity for it (indeed,
some macros required by the C Standard itself are lower-case).
People are accustomed to seeing macro names in upper-case only,
and since macros can look like functions but behave differently
(consider `x = MIN(y,z)' vs `x = MIN(y, f_with_side_effects())'),
the coder must sometimes know which is being used.  Recommendation:
Stick with upper-case macro names to forestall confusion.

> 2. My personal variable and function naming style is camel case, with
> variable names beginning with a lower case char and function names not.
> Is that acceptable, if not what is?
>
> EG:
> Variables: int numFiles = 0;
> Functions: int CountNumFilesInDir(char* path);

     Use whatever works for you, and for the others who read the
same body of code.  If you're working on existing code, stay with
whatever conventions it already uses.  If you're writing new code
(that's not in association with existing code), use what you like.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if
> I reach 120 chars I start thinking this might not look great in someone
> else's editor.

     Really long lines -- especially in blocks that cover several
consecutive lines -- can be hard to read because the eye may have
trouble maintaining vertical "registration" while flipping back
and forth between the end of one line and the start of the next --
oh, damn, I skipped down two again!  Usual practice is to use
narrower lines than yours, allowing the line to be seen as a whole
rather than traced out in multiple horizontal jumps.  Seventy to
eighty characters are a typical length (although that range is in
part due to hysterical raisins).

> 4. Does anyone care where the pointer * is? I prefer keeping to next to
> the type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;

     If you're firm about declaring only one identifier per line,
this is fine.  But the minute you write

	char* firstPtr, finalPtr;

.... you're going to be unpleasantly surprised.

> 5. On a slightly different note, I've been handling my error messages by
> using #define string constants in a header file. I saw some code which
> did this and it looked good to me. Is that standard practise, if not
> what is?
>
> EG. #define ErrorDirNotFound "The directory was not found."

     This could turn out to be helpful in translating the messages
someday: "Das Verzeichnis wurde nicht gefunden."  On the other hand,
there are more flexible ways to deal with this than to compile
separate versions for German, French, Klingon, ...

> There are so many style guides out there, most of them say contradictory
> things at one point or another. What do the pros do?

     Contradict each other, of course!  Why did you ask?

> Finally, before someone points this out... I know if I'm coding for
> myself, and not following somebody else's stylistic requirements, I can
> do whatever I want. However I'd like my code to be 'acceptable looking'
> to the wider UNIX C community.

     From the Eighth Commandment: "... thy creativity is better
used in solving problems than in creating beautiful new impediments
to understanding."  The Commandment speaks of brace styles, but
the point applies with equal force to other stylistic choices.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Reply esosman2 (2945) 2/24/2010 7:50:54 PM

On 02/24/2010 12:35 PM, Poster Matt wrote:
> Hi,
> 
> I've a few questions concerning style when programming C on UNIX systems. I 
> don't want to look like an amateur. :)

> There are so many style guides out there, most of them say contradictory things 
> at one point or another. What do the pros do?

Your questions are valid, but the real answer is that it totally depends
on the project.  If you're contributing to an existing project then you
should follow the coding standards already in place.

If you're starting something totally new, you can do whatever you want.
 That said, most people will be familiar with a few of of the main
standard styles:  linux kernel, K&R, GNU, etc.  It may make sense to
pick one of those that closest matches your preferred style.

I spend most of my time in the kernel, so my answers would be:

1) #defines should be uppercase and words separated with underscores.
Uppercase is also used for enums and name-prefixes that follow a uniform
convention.

1a) Using CamelCase (aka StudlyCaps) is frowned upon partly because it
means that the word-based commands in various editors (emacs, for
instance) don't work properly.

2) lowercase everything separated by underscores

3) max line length is 80 char

4) pointer * is next to variable

5) error messages are in the code explicitly

Chris
0
Reply cbf123 (179) 2/24/2010 8:02:08 PM

Poster Matt <postermatt@no_spam_for_me.org> writes:
> 1. Having been programming in higher level languages for the last 15
> years, I'm finding it hard to get used to DEFINES in all capitals. Is
> it really frowned on not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

The problem with the preprocessor is that it work at the level of
preprocessing tokens and this means that, if preprocessor macros don't
live in a unique namespace, unintended substitutions can happen
easily, for instance, of subroutine names, and errors caused by this
are difficult to track down.

[...]

> 2. My personal variable and function naming style is camel case, with
> variable names beginning with a lower case char and function names
> not. Is that acceptable, if not what is?
>
> EG:
> Variables: int numFiles = 0;
> Functions: int CountNumFilesInDir(char* path);

CamelCase was invented for the Xerox Alto whose keyboard didn't have
an underscore character. Since 'object oriented programming' was also
(mostly) invented in the same context, 'OO-programmers' of today still
work around this hardware deficiency of the 1970s.
TheReasonThatTextsAreNotWrittenLikeThisIsBecauseReadibiltyIsCrappyThen.
So_use_a_visually_distinct_separator_character. People using scripts
based on the Roman alphabet have abandoned the Roman writing
convention to not use separators more than thousand years ago. Don't
reinvent it.

[...]

> 4. Does anyone care where the pointer * is? I prefer keeping to next
> to the type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;

C knows about three kinds of derived types, arrays

	char a[];

Pointers to functions

	char (*a)();

and pointers

	char *a;

Don't special-case on of these three cases because of a lack of
understanding of the C type system.

Lastly, please don't ask questions like this in public.
0
Reply rweikusat (2679) 2/24/2010 8:05:03 PM

Poster Matt <postermatt@no_spam_for_me.org> writes:
> I've a few questions concerning style when programming C on UNIX
> systems. I don't want to look like an amateur. :)
>
> 1. Having been programming in higher level languages for the last 15
> years, I'm finding it hard to get used to DEFINES in all capitals. Is
> it really frowned on not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

The convention is to use all-caps for macro names, unless you're
deliberately hiding the fact that something is a macro.

> 2. My personal variable and function naming style is camel case, with
> variable names beginning with a lower case char and function names
> not. Is that acceptable, if not what is?
>
> EG:
> Variables: int numFiles = 0;
> Functions: int CountNumFilesInDir(char* path);

A lot of people dislike camel case (my own preference is lower case
with underscores for most things), but it's a common and widely
accepted style.  If you're working on an existing project, you should
follow the existing style (this applies to all these rules).

> 3. Is there an accepted maximum line length? I've got a 24" monitor,
> if I reach 120 chars I start thinking this might not look great in
> someone else's editor.

80 columns.

> 4. Does anyone care where the pointer * is? I prefer keeping to next
> to the type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;

The usual C style is
    char *firstName;
The usual C++ style is
    char* firstName;
There's no language-level reason for the difference; C and C++ syntax
are the same at this level.  I think it's just that Kernighan and
Ritchie preferred the first form, and Stroustrup preferred the second.

If you're going to be programming in C, I recommend the first form,
both because it's the usual convention and because it follows the
syntax of the langauge.  When the compiler parses:

    char * firstName ;

"*" and "firstName" are grouped together.  What the declaration really
means is that the expression "*firstName" is of type char; it follows
from this that firstName is of type char*.  C declarations usually
follow a "declaration follows use" format (though not 100%
consistently).

If you choose to use the second style, you should avoid declaring
multiple objects in a single declaration.  Others have pointed out
that this:
    char* foo, bar;
is either misleading or wrong.  The solution, whichever style you
use, is to declare foo and bar separately:

    char *foo; /* or char* foo; if you insist */
    char bar;

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 8:41:16 PM

On Feb 24, 12:32=A0pm, Seebs <usenet-nos...@seebs.net> wrote:
> On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:
<snip>
> > 2. My personal variable and function naming style is camel case, with v=
ariable
> > names beginning with a lower case char and function names not. Is that
> > acceptable, if not what is?
>
> I dislike it, anyway. =A0Convention is words_with_underscores().
>
> > EG:
> > Variables: int numFiles =3D 0;
> > Functions: int CountNumFilesInDir(char* path);

FWIW, I prefer the camel case style, though I don't capitalize
function names.  If I'm maintaining someone else's code (and don't
expect to take it over), I follow their style.  If I'm working with a
team, the team usually agrees on a style.
<snip>

> > 4. Does anyone care where the pointer * is? I prefer keeping to next to=
 the
> > type, rather than next to the variable name.
> > EG. I like: char* firstName; and not so much: char *firstName;
>
> You are wrong.
>
> I mean, sure, it compiles, but consider:
>
> =A0 =A0 =A0 =A0 char* x, y;
>
> By contrast:
> =A0 =A0 =A0 =A0 char *x, y;
> makes it clear that you are aware that the * modifies the variable, not t=
he
> type.

Absolutely with Seebs on this.  The first style clearly implies that x
and y are both pointers to characters.

<snip>

I would like to add that, as long as you're trying to use good style,
for God's sake don't use the wrong indentation style.  If you put your
opening braces on the same line as your conditional, you'll just look
like a fool in front of your friends and colleagues.
0
Reply bruces42 (69) 2/24/2010 8:53:32 PM

Rainer Weikusat <rweikusat@mssgmbh.com> writes:
> Poster Matt <postermatt@no_spam_for_me.org> writes:
[...]
>> 4. Does anyone care where the pointer * is? I prefer keeping to next
>> to the type, rather than next to the variable name.
>>
>> EG. I like: char* firstName; and not so much: char *firstName;
>
> C knows about three kinds of derived types, arrays
>
> 	char a[];
>
> Pointers to functions
>
> 	char (*a)();
>
> and pointers
>
> 	char *a;

Array types, structure types, union types, function types, and pointer
types are all derived types (C99 6.2.5).

> Don't special-case on of these three cases because of a lack of
> understanding of the C type system.

But it might be acceptable to special-case on some cases *with*
an understanding of the C type system.  I prefer "char *a;" myself,
but there's a valid argument that "char* a;" makes it more obvious
that's meant (that a is of type char*).  As long as you also avoid
declaring multiple objects in a single declaration, it doesn't
necessarily cause any problems.

> Lastly, please don't ask questions like this in public.

Why not?  Or are you just being rude?

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 9:06:46 PM

On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:

....

> I would like to add that, as long as you're trying to use good style,
> for God's sake don't use the wrong indentation style. =A0If you put your
> opening braces on the same line as your conditional, you'll just look
> like a fool in front of your friends and colleagues.

Snobbish nonsense!


0
Reply james.harris.1 (384) 2/24/2010 9:28:12 PM

On Feb 24, 2:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:


> There are so many style guides out there, most of them say contradictory =
things
> at one point or another. What do the pros do?


Among other things write style guides.
(i.e. what makes you think the pros are
not contradictory)

The only near universal conventions that I can
identify are

   - macros should be upper case
   - lines should not exceed 80 characters

For the rest, choose what you are most comfortable
with, always remembering that good code comes first.

(There have been lots of pros and cons pointed
out for your chosen style.  I have little to add;
putting all error strings in one place seems
like a good idea, but something a little more flexible
than simple macros would seem in order.)

                  - William Hughes






>
> Finally, before someone points this out... I know if I'm coding for mysel=
f, and
> not following somebody else's stylistic requirements, I can do whatever I=
 want.
> However I'd like my code to be 'acceptable looking' to the wider UNIX C c=
ommunity.
>
> Thanks and regards, etc.

0
Reply wpihughes (390) 2/24/2010 9:30:48 PM

In article <slrnhob00o.fh7.usenet-nospam@guild.seebs.net>, Seebs <usenet-nospam@seebs.net> writes:
> On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>> 1. Having been programming in higher level languages for the last 15 years, I'm 
>> finding it hard to get used to DEFINES in all capitals. Is it really frowned on 
>> not to do so? Is CamelCase acceptable?
> 
> It'll work, but people will find it surprising.  All-caps as a warning that
> something is a macro or other manifest constant is pretty canonical.
> 
> But you'd normally spell that one "MAX_FILES".

(
And not FILES_MAX, as _MAX is a reserved suffix (in the X/Open (or
POSIX) Name Space).

http://www.opengroup.org/onlinepubs/007908775/xsh/compilation.html#tag_000_002_001
http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_02_02
)


>> 2. My personal variable and function naming style is camel case, with variable 
>> names beginning with a lower case char and function names not. Is that 
>> acceptable, if not what is?
> 
> I dislike it, anyway.  Convention is words_with_underscores().

I agree. However, I'd like to mention, as a counter-example, some C
language X client libs using CamelCase.

http://en.wikipedia.org/wiki/Xlib
http://en.wikipedia.org/wiki/Intrinsics
http://en.wikipedia.org/wiki/Motif_(widget_toolkit)


>> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach 
>> 120 chars I start thinking this might not look great in someone else's editor.
> 
> 80ish is preferred.  Lines exceeding 80 will generally not be accepted by a
> lot of projects unless there's a VERY good reason.

Yes, a source formatted 80 columns wide works nicely on a character
console. And on a 24" TFT in 1920x1200, you can put two such windows
side by side, or have a web browser or a PDF viewer open beside the
source window, or diff two versions side by side without having to
scroll horizontally.


>> 5. On a slightly different note, I've been handling my error messages by using 
>> #define string constants in a header file. I saw some code which did this and it 
>> looked good to me. Is that standard practise, if not what is?
> 
>> EG. #define ErrorDirNotFound "The directory was not found."
> 
> No.  Look into gettext() if you need to do this, or just put them in
> literally.

Or, for a bit more portable (and harder to use) approach:

http://www.opengroup.org/onlinepubs/007908775/xsh/catopen.html
http://www.opengroup.org/onlinepubs/007908775/xcu/gencat.html

The idea is that you translate printf() style format strings into
different natural languages, making heavy use of %n$ "position
specifiers", so that you can change the order the arguments are printed
in, without changing the order they are passed to *printf() (ie. without
changing the code).

http://www.opengroup.org/onlinepubs/007908775/xsh/fprintf.html#tag_000_008_809

catgets() allows/forces the programmer to supply a default string, which
is very useful.

(Not that I'd believe in software internationalization at all, having
seen *no* software correctly *and* understandably translated from
English to Hungarian, for example.)


> It's odd that you've managed
> a complete sweep of, for every stylistic decision described above, picking
> the opposite of the general convention in the UNIX world.  Where did you pick
> up these preferences?

I'd have guessed Java, but as Rainer Weikusat points out in
<87d3zuflhs.fsf@fever.mssgmbh.com>, CamelCase and co. originate from
much earlier. (Thanks for the interesting historical tidbit, Rainer!)

Cheers,
lacos
0
Reply lacos (176) 2/24/2010 9:49:15 PM

In article <7f8b94fc-a78e-4c64-becf-f70a3843de08@o3g2000yqb.googlegroups.com>, James Harris <james.harris.1@googlemail.com> writes:
> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
> 
> ...
> 
>> I would like to add that, as long as you're trying to use good style,
>> for God's sake don't use the wrong indentation style.  If you put your
>> opening braces on the same line as your conditional, you'll just look
>> like a fool in front of your friends and colleagues.
> 
> Snobbish nonsense!

I've actually laughed out loud when I've read Bruce's part above; it's
so blatant that I'm almost completely sure it was meant as irony.
(Perhaps so is your response, too.)

Cheers,
lacos
0
Reply lacos (176) 2/24/2010 9:54:38 PM

On 24 Feb 2010 12:35, Poster Matt wrote:
> I've a few questions concerning style when programming C on UNIX
> systems. I don't want to look like an amateur. :)

The biggest mistakes that newbies make are lack of consistency and
trying to change others' style.  If you're contributing to an existing
project, follow whatever established style it has, period.

If you're starting a new project, pick one of the common styles in other
projects you've seen and like.  Do not modify (or "customize") the style
unless you can competently explain _why_ it does things the way it does
and you can demonstrate (to people more skilled than you) that your
change is an improvement for your particular project.

Do not invent your own style.

> 1. Having been programming in higher level languages for the last 15
> years, I'm finding it hard to get used to DEFINES in all capitals. Is it
> really frowned on not to do so? Is CamelCase acceptable?
> 
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

This is canonical and is done in all of the various styles I've seen.
There are very good reasons for that.

(It's more important for function-like macros, where you may need to
warn the user that arguments may be evaluated multiple times.  OTOH,
function-like macros that mask a true function must use the case of the
function they mask, but must take care not to do multiple evaluation.)

> 2. My personal variable and function naming style is camel case, with
> variable names beginning with a lower case char and function names not.
> Is that acceptable, if not what is?
> 
> EG:
> Variables: int numFiles = 0;

This is camelCase.

> Functions: int CountNumFilesInDir(char* path);

This is PascalCase.

Mixing the two in the same project will drive adherents of _both_ styles
nuts.  Pick one and stick to it; that way you'll only drive half of your
readers nuts.

(There's also this_type_of_identifier; the same logic applies, i.e.
don't mix that with either of the above.  Never, never create some
God-awful hybrid with both underscores and uppercase letters...)

Some mixing is unavoidable if you call libraries that use different
styles, but don't deliberately make it worse.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if
> I reach 120 chars I start thinking this might not look great in someone
> else's editor.

Do not go over 80 columns without a very, very good reason.

If that presents a serious problem (i.e. more than the occasional
complicated function call or if expression), there's probably something
wrong with your code anyway.

> 4. Does anyone care where the pointer * is? I prefer keeping to next to
> the type, rather than next to the variable name.
> 
> EG. I like: char* firstName; and not so much: char *firstName;

The latter is canonical in all styles.  If you use the former, one day
you'll write "char* firstName, lastName;" and cause all sorts of problems.

> 5. On a slightly different note, I've been handling my error messages by
> using #define string constants in a header file. I saw some code which
> did this and it looked good to me. Is that standard practise, if not
> what is?
> 
> EG. #define ErrorDirNotFound "The directory was not found."

Either put the string inline or use some facility such as gettext(),
which is better for later i18n issues anyway.

> There are so many style guides out there, most of them say contradictory
> things at one point or another. What do the pros do?

See comments at top.

> Finally, before someone points this out... I know if I'm coding for
> myself, and not following somebody else's stylistic requirements, I can
> do whatever I want. However I'd like my code to be 'acceptable looking'
> to the wider UNIX C community.

If your code will be read by someone else, you want the style to seem
familiar enough to them that it won't distract them from being able to
read what the code _means_; that generally means picking one of the
common styles even if it's not ideal according to your tastes.

If you're absolutely sure _nobody_ will _ever_ read your code, do
whatever you want--but I'd recommend picking a common style anyway just
in case you're wrong.  People usually are about such things, eventually.

S

-- 
Stephen Sprunk         "God does not play dice."  --Albert Einstein
CCIE #3723         "God is an inveterate gambler, and He throws the
K5SSS        dice at every possible opportunity." --Stephen Hawking
0
Reply stephen (1122) 2/24/2010 9:58:50 PM

Stephen Sprunk <stephen@sprunk.org> writes:
> On 24 Feb 2010 12:35, Poster Matt wrote:
[...]
>> EG:
>> Variables: int numFiles = 0;
>
> This is camelCase.
>
>> Functions: int CountNumFilesInDir(char* path);
>
> This is PascalCase.
>
> Mixing the two in the same project will drive adherents of _both_ styles
> nuts.  Pick one and stick to it; that way you'll only drive half of your
> readers nuts.

His convention apparently is to use camelCase for variables and
PascalCase for functions.  It's not necessarily a style I'd use, but
it's not obviously horrible (and it's more or less the style I use
at work).  As with most of these rules, conforming to existing code
is far more important than any benefits of one style over another.
I really dislike the brace placement of the code I work on, but
mixing my own style into it would be far worse (and wouldn't survive
a code review anyway).

> (There's also this_type_of_identifier; the same logic applies, i.e.
> don't mix that with either of the above.  Never, never create some
> God-awful hybrid with both underscores and uppercase letters...)

Again, This_Type_Of_Identifier isn't obviously horrible.  (I use it
myself, though not in C.)

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 10:04:25 PM

On Feb 24, 4:53=A0pm, BruceS <bruce...@hotmail.com> wrote:

> I would like to add that, as long as you're trying to use good style,
> for God's sake don't use the wrong indentation style. =A0If you put your
> opening braces on the same line as your conditional, you'll just look
> like a fool in front of your friends and colleagues.

You need to fix your misprint.  Clearly you meant

If you *dont* put your  opening braces on
the same line as your conditional, you'll
just look like a fool in front of your
friends and colleagues.

                  - William Hughes
0
Reply wpihughes (390) 2/24/2010 10:04:54 PM

Poster Matt <postermatt@no_spam_for_me.org> writes:
>Hi,
>
>I've a few questions concerning style when programming C on UNIX systems. I 
>don't want to look like an amateur. :)
>
>1. Having been programming in higher level languages for the last 15 years, I'm 
>finding it hard to get used to DEFINES in all capitals. Is it really frowned on 
>not to do so? Is CamelCase acceptable?
>
>EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

Well, defines are macros, not constants, so I try to avoid them for this use.
With C99 and C++, one should probably use static const
<type> (where type a signed or unsigned integer of the appropriate width).

e.g.
  static const unsigned int MaxNumFiles = 1024;

For C++, the visibility should be the most restrictive possible
(i.e. private if the constant is only used by class members).

This allows the compiler to use more strict type checking with the
constants, and signedness is explicit.

>
>
>2. My personal variable and function naming style is camel case, with variable 
>names beginning with a lower case char and function names not. Is that 
>acceptable, if not what is?
>
>EG:
>Variables: int numFiles = 0;
>Functions: int CountNumFilesInDir(char* path);

There are many different conventions;   I prefer underscores myself.

I also prefer
int
count_dir_entries(const char *path)

or
inline int
c_class::count_dir_entries(const char *path)

(With vi/vim, ^functioname will move the cursor to start of
the function if it starts the line).

>
>
>3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach 
>120 chars I start thinking this might not look great in someone else's editor.
>

80.  Please.



>
>5. On a slightly different note, I've been handling my error messages by using 
>#define string constants in a header file. I saw some code which did this and it 
>looked good to me. Is that standard practise, if not what is?
>
>EG. #define ErrorDirNotFound "The directory was not found."

Bad practice.  The string value will be duplicated in every compilation
unit that uses it.   Better is to have a function that returns a const char *
given an error message number (e.g. strerror(3)).

In general, for your own code, follow what you like (or your employer requires).

If you are modifying existing code, follow the existing style.

scott
0
Reply scott 2/24/2010 10:06:55 PM

James Harris <james.harris.1@googlemail.com> writes:
>On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>
>...
>
>> I would like to add that, as long as you're trying to use good style,
>> for God's sake don't use the wrong indentation style. =A0If you put your
>> opening braces on the same line as your conditional, you'll just look
>> like a fool in front of your friends and colleagues.
>
>Snobbish nonsense!
>
>

Indeed.

   if (condition) {

is preferred over

   if (condition)
   {

Makes it much more likely that a properly written function will fit on a single
page/screen.

In 30 years of C programming, no employer or project has used the latter form.

scott
0
Reply scott 2/24/2010 10:09:43 PM

Chris Friesen <cbf123@mail.usask.ca> writes:
>On 02/24/2010 12:35 PM, Poster Matt wrote:

>5) error messages are in the code explicitly

In order to effectively i18n the code, this practice should
be avoided.  Rather, one should use gettext or equiv.

scott
0
Reply scott 2/24/2010 10:11:13 PM

On Feb 24, 12:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org>
wrote:
> Hi,
>
> I've a few questions concerning style when programming C on UNIX systems.=
 I
> don't want to look like an amateur. :)
>
> 1. Having been programming in higher level languages for the last 15 year=
s, I'm
> finding it hard to get used to DEFINES in all capitals. Is it really frow=
ned on
> not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.
>

As see from the umpteen replies, you are not going to get one answer
when it comes to a style-related question.

Haven't seen anyone point this out:

Rather than -

  #define MAXNUMFILES 1024

- prefer -

  const int MaxNumFiles =3D 1024;


That way your preprocessor won't do as much damage.
0
Reply mailto.anand.hariharan (147) 2/24/2010 10:12:21 PM

In article <3qhhn.9821$8y6.7846@news.usenetserver.com>, scott@slp53.sl.home (Scott Lurndal) writes:

>   static const unsigned int MaxNumFiles = 1024;
>
> [...]
> 
> This allows the compiler to use more strict type checking with the
> constants, and signedness is explicit.

#define MAX_FILES 1024u
#define BUFSIZE   ((size_t)4096)

(Yes, when I *use* MAX_FILES, I don't necessarily remember its type. But
in that situation the same applies to "MaxNumFiles": we have to look up
the definition.)

Signedness is equally explicit in

#define MAX_FILES 1024

as 1024 is ((int)1024) -- that macro definition is just ugly.

Cheers,
lacos
0
Reply lacos (176) 2/24/2010 10:25:11 PM

Scott Lurndal wrote:
<snip>

> 
>    if (condition) {
> 
> is preferred over
> 
>    if (condition)
>    {

Except, of course, by people who prefer the latter to the former.

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/24/2010 10:33:32 PM

Anand Hariharan wrote:
<snip>

> Haven't seen anyone point this out:
> 
> Rather than -
> 
>   #define MAXNUMFILES 1024
> 
> - prefer -
> 
>   const int MaxNumFiles = 1024;
> 
> 
> That way your preprocessor won't do as much damage.

Fine in C99, I think, but an issue in C90 if he's using it to define an 
array size.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/24/2010 10:34:30 PM

On Feb 24, 4:34=A0pm, Richard Heathfield <r...@see.sig.invalid> wrote:
> Anand Hariharan wrote:
>
> <snip>
>
> > Haven't seen anyone point this out:
>
> > Rather than -
>
> > =A0 #define MAXNUMFILES 1024
>
> > - prefer -
>
> > =A0 const int MaxNumFiles =3D 1024;
>
> > That way your preprocessor won't do as much damage.
>
> Fine in C99, I think, but an issue in C90 if he's using it to define an
> array size.
>

Good point (and that's probably why no one mentioned it?).  Even in
C99, it is not your good old array but a 'Variable' Length Array.

Does the standard have anything to say about VLAs being automatic
storage or free store, but cleans itself up when they go out of scope?

0
Reply mailto.anand.hariharan (147) 2/24/2010 10:42:50 PM

Richard Heathfield <rjh@see.sig.invalid> writes:

> Anand Hariharan wrote:
> <snip>
>
>> Haven't seen anyone point this out:
>>
>> Rather than -
>>
>>   #define MAXNUMFILES 1024
>>
>> - prefer -
>>
>>   const int MaxNumFiles = 1024;
>>
>>
>> That way your preprocessor won't do as much damage.
>
> Fine in C99, I think, but an issue in C90 if he's using it to define
> an array size.

It's a problem in C99 too, if the array is defined at file scope or it
has internal linkage.  There are other reasons why it's not a great
idea in C99.  They stem from the fact that MaxNumFiles is not
permitted as part of a constant expression.  There are several slight
variations depending on what sort of constant expression is required
but I think the simplest things is to say that using the above will
confuse someone sometime and is therefore not usually considered good
style even in C99.

-- 
Ben.
0
Reply ben.usenet (6515) 2/24/2010 10:46:38 PM

Keith Thompson <kst-u@mib.org> writes:
> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>> Poster Matt <postermatt@no_spam_for_me.org> writes:
> [...]
>>> 4. Does anyone care where the pointer * is? I prefer keeping to next
>>> to the type, rather than next to the variable name.
>>>
>>> EG. I like: char* firstName; and not so much: char *firstName;
>>
>> C knows about three kinds of derived types, arrays
>>
>> 	char a[];
>>
>> Pointers to functions
>>
>> 	char (*a)();
>>
>> and pointers
>>
>> 	char *a;
>
> Array types, structure types, union types, function types, and pointer
> types are all derived types (C99 6.2.5).

Exercise for the reader: Which of the six types defined above are
irrelevant for this statement about 'declaration of derived types'
because they belong to a different syntactical class than the three
examples? Which type is irrelevant because it cannot directly appear
in a variable declaration? Which other class of types should appear
instead because they can?

>> Don't special-case on of these three cases because of a lack of
>> understanding of the C type system.
>
> But it might be acceptable to special-case on some cases *with*
> an understanding of the C type system.  I prefer "char *a;" myself,
> but there's a valid argument that "char* a;" makes it more obvious
> that's meant (that a is of type char*).

A type 'char*' doesn't exist. A type named 'char' does, and assuming
that T names an existing type, an object can be declared as 'pointer
to a T' by using the syntax

	T *o;

'Pointerness' is an attribute of the object, not of the type. This is
also consistent with the original intention behind this syntax, namely
that 'declaration should resemble use'.         

[...]

>> Lastly, please don't ask questions like this in public.
>
> Why not?  Or are you just being rude?

They are bound to end up as quite useless quarrels between people
who desire to write "beautiful" code and people who desire to write
readable code.
0
Reply rweikusat (2679) 2/24/2010 10:46:48 PM

scott@slp53.sl.home (Scott Lurndal) writes:
> Poster Matt <postermatt@no_spam_for_me.org> writes:
[...]
>> 1. Having been programming in higher level languages for the last 15
>> years, I'm finding it hard to get used to DEFINES in all
>> capitals. Is it really frowned on not to do so? Is CamelCase
>> acceptable?
>>
>> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

I agree that MAXNUMFILES is harder to read than MaxNumFiles.  The
solution is to write it as MAX_NUM_FILES.

> Well, defines are macros, not constants, so I try to avoid them for this use.
> With C99 and C++, one should probably use static const
> <type> (where type a signed or unsigned integer of the appropriate width).
[...]

Even in C99, the name of a static const object cannot be used as a
constant expression.  This:

    static const int max = 42;
    int arr[max];

is valid in C99, but only because arr is a VLA (though the compiler
might implement it exactly as if it were a non-VLA).  But max can't be
used in other contexts that requires a constant expression, such as
case labels.

A common trick is to use enum:

    enum { max = 42 };

This has the drawback that it can only be of type int.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 10:48:41 PM

Keith Thompson <kst-u@mib.org> writes:
[...]
> His convention apparently is to use camelCase for variables and
> PascalCase for functions.  It's not necessarily a style I'd use, but
> it's not obviously horrible (and it's more or less the style I use
> at work).

On re-reading, I realize that sounds a bit odd.  What I meant is that
it's not necessarily a style I'd use *voluntarily*, but I have no
problem using it if it's necessary to conform to the existing style of
the code I'm working on.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 10:55:32 PM

Rainer Weikusat <rweikusat@mssgmbh.com> writes:
> Keith Thompson <kst-u@mib.org> writes:
>> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>>> Poster Matt <postermatt@no_spam_for_me.org> writes:
>> [...]
>>>> 4. Does anyone care where the pointer * is? I prefer keeping to next
>>>> to the type, rather than next to the variable name.
>>>>
>>>> EG. I like: char* firstName; and not so much: char *firstName;
>>>
>>> C knows about three kinds of derived types, arrays
>>>
>>> 	char a[];
>>>
>>> Pointers to functions
>>>
>>> 	char (*a)();
>>>
>>> and pointers
>>>
>>> 	char *a;
>>
>> Array types, structure types, union types, function types, and pointer
>> types are all derived types (C99 6.2.5).
>
> Exercise for the reader: Which of the six types defined above are
> irrelevant for this statement about 'declaration of derived types'
> because they belong to a different syntactical class than the three
> examples? Which type is irrelevant because it cannot directly appear
> in a variable declaration? Which other class of types should appear
> instead because they can?

You said that "C knows about three kinds of derived types".  In fact,
there are six.  I was disputing the accuracy of your statement, not
its relevance.

>>> Don't special-case on of these three cases because of a lack of
>>> understanding of the C type system.
>>
>> But it might be acceptable to special-case on some cases *with*
>> an understanding of the C type system.  I prefer "char *a;" myself,
>> but there's a valid argument that "char* a;" makes it more obvious
>> that's meant (that a is of type char*).
>
> A type 'char*' doesn't exist. A type named 'char' does, and assuming
> that T names an existing type, an object can be declared as 'pointer
> to a T' by using the syntax
>
> 	T *o;
>
> 'Pointerness' is an attribute of the object, not of the type. This is
> also consistent with the original intention behind this syntax, namely
> that 'declaration should resemble use'.         

Wrong.  char* is a type.  Specifically, it's a derived type and a
pointer type.  See C99 6.2.5, particularly paragraph 20.

If char* is not a type, can you explain what exactly you mean when you
use the word "type"?  Your usage appears to be inconsistent with the
usage in the C standard.

You might have a valid point in there somewhere, but your misuse of
terminology makes it difficult to discuss it.

(And for the record, I agree that "T *o;" is preferable to
"T* o;"; I just don't agree that it's a huge deal.)

> [...]
>
>>> Lastly, please don't ask questions like this in public.
>>
>> Why not?  Or are you just being rude?
>
> They are bound to end up as quite useless quarrels between people
> who desire to write "beautiful" code and people who desire to write
> readable code.

Perhaps, but we've also seen some useful discussion in this thread,
particularly the point about the importance of conforming to whatever
coding standard is used for an existing project.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/24/2010 11:15:50 PM

On Feb 24, 5:04=A0pm, William Hughes <wpihug...@hotmail.com> wrote:
> On Feb 24, 4:53=A0pm, BruceS <bruce...@hotmail.com> wrote:
>
> > I would like to add that, as long as you're trying to use good style,
> > for God's sake don't use the wrong indentation style. =A0If you put you=
r
> > opening braces on the same line as your conditional, you'll just look
> > like a fool in front of your friends and colleagues.
>
> You need to fix your misprint. =A0Clearly you meant
>
> If you *dont* put your =A0opening braces on
> the same line as your conditional, you'll
> just look like a fool in front of your
> friends and colleagues.
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 - William Hughes

You both are wrong.  It's best to mix the two styles, to get the best
of both worlds.

if ( conditional ) {
  // line of code
} else {
  // line of code
}

if ( conditional )
{
  // multiple
  // lines
  // of
  // code
}
else
{
  // multiple
  // lines
  // of
  // code
}

if ( conditional ) {
  // line of code
}
else
{
  // multiple
  // lines
  // of
  // code
}

and yes this is actually my personal style :P
0
Reply jadill33 (201) 2/24/2010 11:17:02 PM

>
>>
>> Lastly, please don't ask questions like this in public.
>>
> Why not? Or are you just being rude?
>
Didn't you know?  Source code style is a shameful secret, to be 
practiced behind closed doors by consenting adults only.

I saw the subject of the first post in this thread, and immediately 
thought that there's a quick way to get one of the largest threads in 
the newsgroup.

0
Reply J.deBoynePollard-newsgroups (95) 2/24/2010 11:20:07 PM

On 24 Feb 2010 22:09:43 GMT
scott@slp53.sl.home (Scott Lurndal) wrote:

> 
>    if (condition) {
> 
> is preferred over
> 
>    if (condition)
>    {
> 
> Makes it much more likely that a properly written function will fit
> on a single page/screen.

Hmmm...

if (condition) {    <-- one line

if (condition)      <-- one line
{                   <-- and another one, makes two lines

Does that really make a BIG difference?  

> 
> In 30 years of C programming, no employer or project has used the
> latter form.

Really? What's so bad about that? I prefer the latter btw...


0
Reply vlllnz (22) 2/25/2010 12:30:13 AM

Scott Lurndal wrote:
> James Harris <james.harris.1@googlemail.com> writes:
>> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>
>> ...
>>
>>> I would like to add that, as long as you're trying to use good style,
>>> for God's sake don't use the wrong indentation style. =A0If you put your
>>> opening braces on the same line as your conditional, you'll just look
>>> like a fool in front of your friends and colleagues.
>> Snobbish nonsense!
>>
>>
> 
> Indeed.
> 
>    if (condition) {
> 
> is preferred over
> 
>    if (condition)
>    {

By whom?

> Makes it much more likely that a properly written function will fit on a single
> page/screen.

If the extra lines required for an opening brace are an issue, the 
function isn't properly written!

> In 30 years of C programming, no employer or project has used the latter form.

I can honestly negate that line.

-- 
Ian Collins
0
Reply ian-news (9878) 2/25/2010 12:43:10 AM

Ian Collins wrote:
> Scott Lurndal wrote:
<snip>
>>    if (condition) {
>>
>> is preferred over
>>
>>    if (condition)
>>    {
> 
> By whom?

Scott Lurndal (and plenty of other people, of whom I am not one).

<snip>

>> In 30 years of C programming, no employer or project has used the 
>> latter form.
> 
> I can honestly negate that line.

In fairness to Scott, I think he just intended to describe his personal 
experience. In my own experience, Allman style (i.e. the latter of the 
two styles quoted above) is almost universal. I can't actually call to 
mind a single project where 1TBS was used - but there must have been at 
least one; my memory isn't what it... um... ah!... was.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/25/2010 1:29:12 AM

In article <Hshhn.9822$8y6.5647@news.usenetserver.com>,
Scott Lurndal <slp53@pacbell.net> wrote:
>
>   if (condition) {
>
>is preferred over
>
>   if (condition)
>   {
>
>Makes it much more likely that a properly written function will fit on
>a single page/screen.

And then there are people who write like this:

    if (condition) {

        do_something();
        do_another_thing();
    }
0
Reply ike5 (222) 2/25/2010 8:40:28 AM

> And then there are people who write like this:
>
>      if (condition) {
>
>          do_something();
>          do_another_thing();
>      }

or like this:
    if (condition)
       {
       do_something();
       do_another_thing();
       }

or even like this:
    if (condition) { do_something(); do_another_thing(); }

.... the world is a cruel place!

0
Reply Rainer_Temme (45) 2/25/2010 9:56:21 AM

BruceS <bruces42@hotmail.com> wrote:

> I would like to add that, as long as you're trying to use good style,
> for God's sake don't use the wrong indentation style.  If you put your
> opening braces on the same line as your conditional, you'll just look
> like a fool in front of your friends and colleagues.

Yeah. Those Kernighan and Ritchie guys knew jack shit about C.

Richard
0
Reply raltbos (821) 2/25/2010 12:12:42 PM

Seebs <usenet-nospam@seebs.net> wrote:

> On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:
> > 5. On a slightly different note, I've been handling my error messages by using 
> > #define string constants in a header file. I saw some code which did this and it 
> > looked good to me. Is that standard practise, if not what is?
> 
> > EG. #define ErrorDirNotFound "The directory was not found."
> 
> No.  Look into gettext() if you need to do this, or just put them in
> literally.

gettext() is nice if you have it (it's POSIX, isn't it? Not ISO, anyway,
but common), but putting the messages in literally only works if you
don't reuse them. IME, _some_ error messages are used more than once, in
which case a #define is nice.

Richard
0
Reply raltbos (821) 2/25/2010 12:12:42 PM

On Feb 24, 7:30=A0pm, Lorenzo Villari <vll...@tiscali.it> wrote:
> On 24 Feb 2010 22:09:43 GMT
>
> sc...@slp53.sl.home (Scott Lurndal) wrote:
>
> > =A0 =A0if (condition) {
>
> > is preferred over
>
> > =A0 =A0if (condition)
> > =A0 =A0{
>
> > Makes it much more likely that a properly written function will fit
> > on a single page/screen.
>
> Hmmm...
>
> if (condition) { =A0 =A0<-- one line
>
> if (condition) =A0 =A0 =A0<-- one line
> { =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <-- and another one, makes two line=
s
>
> Does that really make a BIG difference? =A0
>

The only time it bugs me is when I have a single line of code for an
if and else statement.

if ( condition )
{
  // line
}
else
{
  // other line
}

I used to use this for a while.  But I tried the other convention and
ended up liking it better.  Again, this is for my personal stuff; if a
style is already in place in a project, I follow that standard.

I also don't leave out braces though for single lines since I've been
bitten by that in the past.

if ( condition )
  // line

I always do this

if ( condition ) {
  // line
}

>
> > In 30 years of C programming, no employer or project has used the
> > latter form.
>
> Really? What's so bad about that? I prefer the latter btw...

0
Reply jadill33 (201) 2/25/2010 1:36:25 PM

> Indeed.

>    if (condition) {

> is preferred over

>    if (condition)
>    {

> Makes it much more likely that a properly written function will fit on
> a single page/screen.

> In 30 years of C programming, no employer or project has used the
> latter form.

The standard GNU style (i.e. recommended for GNU projects) is to use

    if (condition)
      {
        blabla
      }

so Emacs uses this style.  I personnally prefer the single-line form (my
windows never have enough lines), so I hacked up some .emacs thingy that
makes the two-line form display as the one-line form.


        Stefan
0
Reply monnier (195) 2/25/2010 2:11:47 PM

Richard Bos wrote:

> gettext() is nice if you have it (it's POSIX, isn't it?

No, gettext() is not in POSIX.  It specifies catopen(), catgets(),
and catclose().  (They used to be in the XSI option, but were made
mandatory in the 2008 revision.)

> Not ISO, anyway,

By "Not ISO" presumably you meant not in the (ISO) C Standard.
You could say "Not ISO C" for that, but "Not ISO" is ambiguous
because POSIX is also an ISO standard.

-- 
Geoff Clare <netnews@gclare.org.uk>


0
Reply geoff31 (365) 2/25/2010 2:24:29 PM

On Feb 25, 2:12=A0pm, ralt...@xs4all.nl (Richard Bos) wrote:
>
>
> Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
>
As CS Lewis said, the first pot, which would prove its maker a genius
if it were the first pot ever made, would prove him a dunce if it came
after many millenia of pot-making.


0
Reply malcolm.mclean5 (721) 2/25/2010 2:33:54 PM

On Feb 24, 4:09=A0pm, sc...@slp53.sl.home (Scott Lurndal) wrote:
>
> =A0 =A0if (condition) {
>
> is preferred over
>
> =A0 =A0if (condition)
> =A0 =A0{
>
> Makes it much more likely that a properly written function will fit on a =
single
> page/screen.
>
> In 30 years of C programming, no employer or project has used the latter =
form.
>
> scott


You've gotten some strong reactions to your not-seen-in-30-years
comment above.

FWIW I use the latter form myself.  However, one good reason I got
from an ex-colleague for using the first style was that if you are
scrolling upward in source code, and get to the closing brace of a
block, using the keyboard shortcut in your editor for jumping to the
matching brace will get you to see the if (or while or for)
condition.  Otherwise, it will only scroll upward to a point where the
opening brace is shown as the first line, and one has to go up one
line more.  To me, this is not a big inconvenience.

- Anand
0
Reply mailto.anand.hariharan (147) 2/25/2010 2:37:18 PM

On 2010-02-25, Richard Heathfield <rjh@see.sig.invalid> wrote:
> In fairness to Scott, I think he just intended to describe his personal 
> experience. In my own experience, Allman style (i.e. the latter of the 
> two styles quoted above) is almost universal. I can't actually call to 
> mind a single project where 1TBS was used - but there must have been at 
> least one; my memory isn't what it... um... ah!... was.

The two that come to mind are Linux and NetBSD.  :)

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 2/25/2010 3:06:32 PM

On Feb 24, 2:54=A0pm, la...@ludens.elte.hu (Ersek, Laszlo) wrote:
> In article <7f8b94fc-a78e-4c64-becf-f70a3843d...@o3g2000yqb.googlegroups.=
com>, James Harris <james.harri...@googlemail.com> writes:
>
> > On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>
> > ...
>
> >> I would like to add that, as long as you're trying to use good style,
> >> for God's sake don't use the wrong indentation style. =A0If you put yo=
ur
> >> opening braces on the same line as your conditional, you'll just look
> >> like a fool in front of your friends and colleagues.
>
> > Snobbish nonsense!
>
> I've actually laughed out loud when I've read Bruce's part above; it's
> so blatant that I'm almost completely sure it was meant as irony.
> (Perhaps so is your response, too.)
>
> Cheers,
> lacos

Well *someone* laughed anyway.  Yes, this was intended ironically, and
I thought it was so obvious that I didn't put in an emoticon.  This is
one of the oldest pointless battles in C.  Now it looks like I've
started it again, rather than the intended humor.  I would have said
something about the inferiority of little-endianism, but I'm afraid
few people really get that.

Years ago, I had my one and only protest shirt.  It said, in big
letters, "STOP PLATE TECTONICS".  So many people were confused by it I
almost gave up wearing it.  Then one Saturday, a manager at my work
started to walk past me, stopped to double-check what my shirt said,
and walked on laughing heartily.
0
Reply bruces42 (69) 2/25/2010 3:57:19 PM

Seebs wrote:
> On 2010-02-25, Richard Heathfield <rjh@see.sig.invalid> wrote:
>> In fairness to Scott, I think he just intended to describe his personal 
>> experience. In my own experience, Allman style (i.e. the latter of the 
>> two styles quoted above) is almost universal. I can't actually call to 
>> mind a single project where 1TBS was used - but there must have been at 
>> least one; my memory isn't what it... um... ah!... was.
> 
> The two that come to mind are Linux and NetBSD.  :)

:-)  Well, again I was referring only to my own experience. I haven't 
actually worked on the source base to those two particular OSen. (Or 
indeed any other mainstream OSen, come to that.)

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/25/2010 3:58:09 PM

On Feb 24, 7:30=A0pm, Lorenzo Villari <vll...@tiscali.it> wrote:
> On 24 Feb 2010 22:09:43 GMT
>
> sc...@slp53.sl.home (Scott Lurndal) wrote:
>
> > =A0 =A0if (condition) {
>
> > is preferred over
>
> > =A0 =A0if (condition)
> > =A0 =A0{
>
> > Makes it much more likely that a properly written function will fit
> > on a single page/screen.
>
> Hmmm...
>
> if (condition) { =A0 =A0<-- one line
>
> if (condition) =A0 =A0 =A0<-- one line
> { =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <-- and another one, makes two line=
s
>
> Does that really make a BIG difference? =A0
>
>
>
> > In 30 years of C programming, no employer or project has used the
> > latter form.
>
> Really? What's so bad about that? I prefer the latter btw...

The only reason I don't use the two-liner is that it's two lines.  If
you write functions with a lot of conditionals (e.g. you're calling
functions that can fail) it adds up really quickly.  It's also another
line you have to indent properly [something a lot of people don't do].

There is no technical reason beyond that for favouring either.

Personally I use the one-liner but I'll work on code that uses the
other.  If I take ownership of code that uses the two liner I might
switch it back to one-liner but beyond that I'm not that petty :-)

my two cents...

Tom
0
Reply tom236 (284) 2/25/2010 4:02:47 PM

On Feb 25, 7:33=A0am, Malcolm McLean <malcolm.mcle...@btinternet.com>
wrote:
> On Feb 25, 2:12=A0pm, ralt...@xs4all.nl (Richard Bos) wrote:
>
> > Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
>
> As CS Lewis said, the first pot, which would prove its maker a genius
> if it were the first pot ever made, would prove him a dunce if it came
> after many millenia of pot-making.

That's a good one; I'll try to remember it.
FWIW, the K&R bit was intentional, to make the joke more obvious.  Not
obvious enough for some, but apparently I either overestimated the
volume in the ng, or underestimated the mass.  My bad.
0
Reply bruces42 (69) 2/25/2010 4:03:08 PM

BruceS wrote:
> On Feb 25, 7:33 am, Malcolm McLean <malcolm.mcle...@btinternet.com>
> wrote:
>> On Feb 25, 2:12 pm, ralt...@xs4all.nl (Richard Bos) wrote:
>>
>>> Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
>> As CS Lewis said, the first pot, which would prove its maker a genius
>> if it were the first pot ever made, would prove him a dunce if it came
>> after many millenia of pot-making.
> 
> That's a good one; I'll try to remember it.
> FWIW, the K&R bit was intentional, to make the joke more obvious.  Not
> obvious enough for some, but apparently I either overestimated the
> volume in the ng, or underestimated the mass.  My bad.

Is it not possible that you underestimated the gravity of the situation?

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/25/2010 4:07:11 PM

Julienne Walker wrote:
> On Feb 24, 2:21 pm, Fred <fred.l.kleinschm...@boeing.com> wrote:
>> On Feb 24, 11:10 am, Julienne Walker <happyfro...@hotmail.com> wrote:
>>> On Feb 24, 1:35 pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>>>> 4. Does anyone care where the pointer * is? I prefer keeping to next to the
>>>> type, rather than next to the variable name.
>>>> EG. I like: char* firstName; and not so much: char *firstName;
>>> Just make sure you're consistent and nobody will care. :-)
>> Except that it is very error-prone to do so.
> 
> It's only error prone if you have multiple variables in a declaration
> statement (which the OP's example did not). That itself is often
> viewed as an unsafe practice.

OP here... Yes and agreed. My view is that each variable should have it's own 
line. The only exception I make is when a for loop needs 2 index variables and 
both are initiated in the for loop statement. EG:

int i, j;
for (i = pos, j = 0; ...)
0
Reply postermatt (37) 2/25/2010 4:18:02 PM

On Feb 24, 12:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org>
wrote:
> Hi,
>
> I've a few questions concerning style when programming C on UNIX systems.=
 I
> don't want to look like an amateur. :)
>
> 1. Having been programming in higher level languages for the last 15 year=
s, I'm
> finding it hard to get used to DEFINES in all capitals. Is it really frow=
ned on
> not to do so? Is CamelCase acceptable?
>
> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.
>

The all-caps convention makes it easier to distinguish preprocessor
macros from other symbols.  This can matter, especially when using
function-like macros (macros that take arguments).  Remember that
macro expansions are simple text substitutions; a macro like

#define square(x) (x*x)

does not compute "x*x" and return a value; it *replaces* the text
"square(x)" with "(x*x)".  If x is "z++", then the replacement text is
"(z++*z++)", which invokes undefined behavior.  If x is "a+b", then
the replacement text is "(a+b*a+b)".  By using all-uppercase for
macros, it makes it easier to see potential red flags like "SQUARE(x+
+)" or "SQUARE(x+y)".

> 2. My personal variable and function naming style is camel case, with var=
iable
> names beginning with a lower case char and function names not. Is that
> acceptable, if not what is?
>
> EG:
> Variables: int numFiles =3D 0;
> Functions: int CountNumFilesInDir(char* path);
>

That's fine.  Just be consistent.

> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I=
 reach
> 120 chars I start thinking this might not look great in someone else's ed=
itor.
>

Side scrolling is irritating.  Just make sure you break lines up
sensibly.

> 4. Does anyone care where the pointer * is? I prefer keeping to next to t=
he
> type, rather than next to the variable name.
>
> EG. I like: char* firstName; and not so much: char *firstName;
>

It's an accident of C lexical rules that you can write it either way.
The second form correctly reflects the language syntax (the '*'
operator is bound to the declarator, not the type specifier), and
tends to be preferred among C programmers.  It also guards against
potential mistakes like

   char* a, b; // b is a regular char

Declarations in C (and C++) reflect the type of an *expression*, not
an object.  The type of the *expression* "*firstName" is char.  The
idea is that the form of the declaration should closely match the form
of an expression that yields a value of that type.  If you have an
array of pointers to int, and you wanted to access a specific int
value, the expression would be "x =3D *a[i];"  The type of the
*expression* "*a[i]" is int, so the declaration of a is "int *a[N]".

C++ programmers prefer "char* firstName", because the type of the
*object* "firstName" is char*.  Fine, but what about "char
lastName[20]"?  The type of "lastName" is "20-element array of char",
but we can't write "char[20] lastName".  Same thing for function
types.  Same thing for pointers to arrays, pointers to functions,
etc.

> 5. On a slightly different note, I've been handling my error messages by =
using
> #define string constants in a header file. I saw some code which did this=
 and it
> looked good to me. Is that standard practise, if not what is?
>
> EG. #define ErrorDirNotFound "The directory was not found."
>
> There are so many style guides out there, most of them say contradictory =
things
> at one point or another. What do the pros do?
>

I can't speak for anyone else, but I typically create a string table
and an enum to index it:

enum ErrorCodes {ErrDirNotFound, ErrInvalidPath, ...};
char ErrorStrings[] =3D {"Directory not found", "Path is invalid", ...};

It scales a little better than using #defines all over the place.

> Finally, before someone points this out... I know if I'm coding for mysel=
f, and
> not following somebody else's stylistic requirements, I can do whatever I=
 want.
> However I'd like my code to be 'acceptable looking' to the wider UNIX C c=
ommunity.
>
> Thanks and regards, etc.

0
Reply jfbode1029 (227) 2/25/2010 4:21:00 PM

On 24 Feb 2010 16:04, Keith Thompson wrote:
> Stephen Sprunk <stephen@sprunk.org> writes:
>> On 24 Feb 2010 12:35, Poster Matt wrote:
> [...]
>>> EG:
>>> Variables: int numFiles = 0;
>>
>> This is camelCase.
>>
>>> Functions: int CountNumFilesInDir(char* path);
>>
>> This is PascalCase.
>>
>> Mixing the two in the same project will drive adherents of _both_ styles
>> nuts.  Pick one and stick to it; that way you'll only drive half of your
>> readers nuts.
> 
> His convention apparently is to use camelCase for variables and
> PascalCase for functions.  It's not necessarily a style I'd use, but
> it's not obviously horrible (and it's more or less the style I use
> at work). 

Granted, it's not as bad as mixing the two within the same type of
thing, but it's still bad, IMHO.

I hate PascalCase; I can deal with it if _everything_ is cased that way,
but a lot of my functions and function calls would end up in camelCase
if I had to switch back and forth.

> As with most of these rules, conforming to existing code
> is far more important than any benefits of one style over another.

Of course; I said roughly the same thing at the top of my post.  I've
just never seen a project that does it that way--or perhaps it was so
painful for me to read that I gave up, moved on, and repressed the memory.

>> (There's also this_type_of_identifier; the same logic applies, i.e.
>> don't mix that with either of the above.  Never, never create some
>> God-awful hybrid with both underscores and uppercase letters...)
> 
> Again, This_Type_Of_Identifier isn't obviously horrible.  (I use it
> myself, though not in C.)

IMHO, that's also horrible.  What I was thinking of was worse, though:
this_typeOfIdentifier.  "Horrible" isn't strong enough for that.

S

-- 
Stephen Sprunk         "God does not play dice."  --Albert Einstein
CCIE #3723         "God is an inveterate gambler, and He throws the
K5SSS        dice at every possible opportunity." --Stephen Hawking
0
Reply stephen (1122) 2/25/2010 4:42:55 PM

>> Where did you pick up these preferences?
> 
> I'd have guessed Java, but as Rainer Weikusat points out in
> <87d3zuflhs.fsf@fever.mssgmbh.com>, CamelCase and co. originate from
> much earlier. (Thanks for the interesting historical tidbit, Rainer!)

OP here...

I picked them up from a university lecturer of mine during a software 
engineering course in the mid 1990's. The course required groups of 5 students 
collaborating on a coding project, don't remember what language we used but 
definitely not C or C++, possibly Java, but not sure.

The lecturer explained that in real world projects with a programming team, a 
style guide would be the norm. So he imposed his own one on us. When free to 
choose, I've been using my own variation of it ever since. It may have been 
influenced by a book called Code Complete, but it's so long since I read it that 
I can't recall exactly what I picked up from that and what from personal 
experience and preference.
0
Reply postermatt (37) 2/25/2010 4:58:25 PM

Eric Sosman wrote:
>>
>     Contradict each other, of course!  Why did you ask?

Given the amount of contradictory advise I'm getting in this
thread I am beginning to wonder why myself. :)
0
Reply postermatt (37) 2/25/2010 5:03:47 PM

On Feb 25, 9:07=A0am, Richard Heathfield <r...@see.sig.invalid> wrote:
> BruceS wrote:
> > On Feb 25, 7:33 am, Malcolm McLean <malcolm.mcle...@btinternet.com>
> > wrote:
> >> On Feb 25, 2:12 pm, ralt...@xs4all.nl (Richard Bos) wrote:
>
> >>> Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
> >> As CS Lewis said, the first pot, which would prove its maker a genius
> >> if it were the first pot ever made, would prove him a dunce if it came
> >> after many millenia of pot-making.
>
> > That's a good one; I'll try to remember it.
> > FWIW, the K&R bit was intentional, to make the joke more obvious. =A0No=
t
> > obvious enough for some, but apparently I either overestimated the
> > volume in the ng, or underestimated the mass. =A0My bad.
>
> Is it not possible that you underestimated the gravity of the situation?

Oh no, the n-body problem, with n>20!  I really *did* mess up.
0
Reply bruces42 (69) 2/25/2010 5:12:38 PM

John Bode <jfbode1029@gmail.com> writes:
[...]
> The all-caps convention makes it easier to distinguish preprocessor
> macros from other symbols.  This can matter, especially when using
> function-like macros (macros that take arguments).  Remember that
> macro expansions are simple text substitutions; a macro like
>
> #define square(x) (x*x)
>
> does not compute "x*x" and return a value; it *replaces* the text
> "square(x)" with "(x*x)".  If x is "z++", then the replacement text is
> "(z++*z++)", which invokes undefined behavior.  If x is "a+b", then
> the replacement text is "(a+b*a+b)".  By using all-uppercase for
> macros, it makes it easier to see potential red flags like "SQUARE(x+
> +)" or "SQUARE(x+y)".
[...]

The side effect problem can't be solved (or at least can't be easily
solved) if you're using a macro, but the operator precedence problem
can.

#define SQUARE(x) ((x)*(x))

You need to parenthesize the entire definition *and* each reference to
the parameter(s).

BTW, here's my favorite example of preprocessor abuse:

#include <stdio.h>

#define SIX 1+5
#define NINE 8+1

int main(void)
{
    printf("%d * %d = %d\n", SIX, NINE, SIX * NINE);
    return 0;
}

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/25/2010 5:15:20 PM

Lorenzo Villari <vlllnz@tiscali.it> writes:
>On 24 Feb 2010 22:09:43 GMT
>scott@slp53.sl.home (Scott Lurndal) wrote:
>
>> 
>>    if (condition) {
>> 
>> is preferred over
>> 
>>    if (condition)
>>    {
>> 
>> Makes it much more likely that a properly written function will fit
>> on a single page/screen.
>
>Hmmm...
>
>if (condition) {    <-- one line
>
>if (condition)      <-- one line
>{                   <-- and another one, makes two lines
>
>Does that really make a BIG difference?

On a 24-line screen, you betcha.

scott
0
Reply scott 2/25/2010 6:12:30 PM

Ian Collins <ian-news@hotmail.com> writes:
>Scott Lurndal wrote:
>> James Harris <james.harris.1@googlemail.com> writes:
>>> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>>
>>> ...
>>>
>>>> I would like to add that, as long as you're trying to use good style,
>>>> for God's sake don't use the wrong indentation style. =A0If you put your
>>>> opening braces on the same line as your conditional, you'll just look
>>>> like a fool in front of your friends and colleagues.
>>> Snobbish nonsense!
>>>
>>>
>> 
>> Indeed.
>> 
>>    if (condition) {
>> 
>> is preferred over
>> 
>>    if (condition)
>>    {
>
>By whom?
>
>> Makes it much more likely that a properly written function will fit on a single
>> page/screen.
>
>If the extra lines required for an opening brace are an issue, the 
>function isn't properly written!
>
>> In 30 years of C programming, no employer or project has used the latter form.
>
>I can honestly negate that line.

Ken and Dennis started the trend, and all my employers (operating system vendors)
have followed it.

This fragment is from c00.c (the Unix V6 C compiler (note the obsolete =& operator!)):

/*
 * Search the keyword table.
 * Ignore initial "." to avoid member-of-structure
 * problems.
 */
findkw()
{
        register struct kwtab *kp;
        register char *p1, *p2;
        char *wp;
        int firstc;

        wp = symbuf;
        firstc = *wp;
        *wp =& 0177;
        for (kp=kwtab; (p2 = kp->kwname); kp++) {
                p1 = wp;
                while (*p1 == *p2++)
                        if (*p1++ == '\0') {
                                cval = kp->kwval;
                                return(1);
                        }
        }
        *wp = firstc;
        return(0);
}

scott
0
Reply scott 2/25/2010 6:18:04 PM

Richard Heathfield <rjh@see.sig.invalid> writes:
>Seebs wrote:
>> On 2010-02-25, Richard Heathfield <rjh@see.sig.invalid> wrote:
>>> In fairness to Scott, I think he just intended to describe his personal 
>>> experience. In my own experience, Allman style (i.e. the latter of the 
>>> two styles quoted above) is almost universal. I can't actually call to 
>>> mind a single project where 1TBS was used - but there must have been at 
>>> least one; my memory isn't what it... um... ah!... was.
>> 
>> The two that come to mind are Linux and NetBSD.  :)
>
>:-)  Well, again I was referring only to my own experience. I haven't 
>actually worked on the source base to those two particular OSen. (Or 
>indeed any other mainstream OSen, come to that.)

Which, aside from a short digression at Verisign, is all that I've
worked on, since Unix V6.

scott
0
Reply scott 2/25/2010 6:19:24 PM

raltbos@xs4all.nl (Richard Bos) writes:
>BruceS <bruces42@hotmail.com> wrote:
>
>> I would like to add that, as long as you're trying to use good style,
>> for God's sake don't use the wrong indentation style.  If you put your
>> opening braces on the same line as your conditional, you'll just look
>> like a fool in front of your friends and colleagues.
>
>Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
>
>Richard

Please take a look at the V6 C compiler (Dennis wrote it himself).

For example:

/*
 * Write out a string, either in-line
 * or in the string temp file labelled by
 * lab.
 */
putstr(lab, amax)
{
        register int c, max;

        nchstr = 0;
        max = amax;
        if (lab) {
                strflg++;
                outcode("BNB", LABEL, lab, BDATA);
                max = 10000;
        } else
                outcode("B", BDATA);
        while ((c = mapch('"')) >= 0) {
                if (nchstr < max) {
                        nchstr++;
                        outcode("1N", c & 0377);
                }
        }
        if (nchstr < max) {
                nchstr++;
                outcode("10");
        }
        outcode("0");
        strflg = 0;
}
0
Reply scott 2/25/2010 6:21:08 PM

Keith Thompson <kst-u@mib.org> writes:
> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>> Keith Thompson <kst-u@mib.org> writes:
>>> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>>>> Poster Matt <postermatt@no_spam_for_me.org> writes:
>>> [...]
>>>>> 4. Does anyone care where the pointer * is? I prefer keeping to next
>>>>> to the type, rather than next to the variable name.
>>>>>
>>>>> EG. I like: char* firstName; and not so much: char *firstName;
>>>>
>>>> C knows about three kinds of derived types, arrays
>>>>
>>>> 	char a[];
>>>>
>>>> Pointers to functions
>>>>
>>>> 	char (*a)();
>>>>
>>>> and pointers
>>>>
>>>> 	char *a;
>>>
>>> Array types, structure types, union types, function types, and pointer
>>> types are all derived types (C99 6.2.5).
>>
>> Exercise for the reader: Which of the six types defined above are
>> irrelevant for this statement about 'declaration of derived types'
>> because they belong to a different syntactical class than the three
>> examples? Which type is irrelevant because it cannot directly appear
>> in a variable declaration? Which other class of types should appear
>> instead because they can?
>
> You said that "C knows about three kinds of derived types".  In fact,
> there are six.  I was disputing the accuracy of your statement, not
> its relevance.

Given that these three kinds of derived types exist, my statement was
accurate. I didn't claim that there weren't any other derived types, I
just didn't write about them because they were irrelvant for the
statement I intended to make (this is, of course, just the same kind
of pointless nitpicking). 

[...]

>>> But it might be acceptable to special-case on some cases *with*
>>> an understanding of the C type system.  I prefer "char *a;" myself,
>>> but there's a valid argument that "char* a;" makes it more obvious
>>> that's meant (that a is of type char*).
>>
>> A type 'char*' doesn't exist. A type named 'char' does, and assuming
>> that T names an existing type, an object can be declared as 'pointer
>> to a T' by using the syntax
>>
>> 	T *o;
>>
>> 'Pointerness' is an attribute of the object, not of the type. This is
>> also consistent with the original intention behind this syntax, namely
>> that 'declaration should resemble use'.         
>
> Wrong.  char* is a type.  Specifically, it's a derived type and a
> pointer type.  See C99 6.2.5, particularly paragraph 20.

	T *o;

is a pointer declarator and it means that the type of o is 'pointer to
T', not 'T*' (6.7.5.1|1).

[...]

> (And for the record, I agree that "T *o;" is preferable to
> "T* o;"; I just don't agree that it's a huge deal.)

It's a pointless inconsistency. 
0
Reply rweikusat (2679) 2/25/2010 7:37:16 PM

Rainer Weikusat <rweikusat@mssgmbh.com> writes:
> Keith Thompson <kst-u@mib.org> writes:
>> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>>> Keith Thompson <kst-u@mib.org> writes:
>>>> Rainer Weikusat <rweikusat@mssgmbh.com> writes:
[...]
>>>>> C knows about three kinds of derived types, arrays
>>>>>
>>>>> 	char a[];
>>>>>
>>>>> Pointers to functions
>>>>>
>>>>> 	char (*a)();
>>>>>
>>>>> and pointers
>>>>>
>>>>> 	char *a;
>>>>
>>>> Array types, structure types, union types, function types, and pointer
>>>> types are all derived types (C99 6.2.5).
>>>
>>> Exercise for the reader: Which of the six types defined above are
>>> irrelevant for this statement about 'declaration of derived types'
>>> because they belong to a different syntactical class than the three
>>> examples? Which type is irrelevant because it cannot directly appear
>>> in a variable declaration? Which other class of types should appear
>>> instead because they can?
>>
>> You said that "C knows about three kinds of derived types".  In fact,
>> there are six.  I was disputing the accuracy of your statement, not
>> its relevance.
>
> Given that these three kinds of derived types exist, my statement was
> accurate. I didn't claim that there weren't any other derived types, I
> just didn't write about them because they were irrelvant for the
> statement I intended to make (this is, of course, just the same kind
> of pointless nitpicking). 

Ok.  I read your statement as implying that C recognizes those three
kinds of derived types and no others.  Thanks for the clarification.

[...]

>>> A type 'char*' doesn't exist. A type named 'char' does, and assuming
>>> that T names an existing type, an object can be declared as 'pointer
>>> to a T' by using the syntax
>>>
>>> 	T *o;
>>>
>>> 'Pointerness' is an attribute of the object, not of the type. This is
>>> also consistent with the original intention behind this syntax, namely
>>> that 'declaration should resemble use'.         
>>
>> Wrong.  char* is a type.  Specifically, it's a derived type and a
>> pointer type.  See C99 6.2.5, particularly paragraph 20.
>
> 	T *o;
>
> is a pointer declarator and it means that the type of o is 'pointer to
> T', not 'T*' (6.7.5.1|1).

So you agree that "pointer to char" is a type, right?  The type
"pointer to char" is commonly referred, using C syntax, as "char*".
I see no problem with referring to it that way.

And if the point you were trying to make was the type often referred
to as "char*" is properly referred to as "pointer to char", that
wasn't at all clear to me from what you wrote.

> [...]
>
>> (And for the record, I agree that "T *o;" is preferable to
>> "T* o;"; I just don't agree that it's a huge deal.)
>
> It's a pointless inconsistency. 

I don't agree that it's entirely pointless, but I'm not going to argue
the point.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/25/2010 7:57:24 PM

On Wed, 24 Feb 2010 22:09:43 +0000, Scott Lurndal wrote:

> James Harris <james.harris.1@googlemail.com> writes:
>>On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>
>>...
>>
>>> I would like to add that, as long as you're trying to use good style,
>>> for God's sake don't use the wrong indentation style. =A0If you put
>>> your opening braces on the same line as your conditional, you'll just
>>> look like a fool in front of your friends and colleagues.
>>
>>Snobbish nonsense!
>>
>>
>>
> Indeed.
> 
>    if (condition) {
> 
> is preferred over
> 
>    if (condition)
>    {

Not by me, it ain't. :)

> Makes it much more likely that a properly written function will fit on a
> single page/screen.

And less likely to catch proper vs improper bracing and indentation, when 
the braces don't line up with the indents.

> In 30 years of C programming, no employer or project has used the latter
> form.

This is one of those cases where there really are legitimate reasons for 
each approach, with the deciding factor being preference.

My take on this has always been to standardize the format "checked in", 
then use indent or some equivalent, on check in and check out, to convert 
between the "checkin format" and the individual coder's preferred format.

0
Reply kbjarnason (4583) 2/26/2010 2:56:31 AM

Kelsey Bjarnason <kbjarnason@gmail.com> writes:

> My take on this has always been to standardize the format "checked in", 
> then use indent or some equivalent, on check in and check out, to convert 
> between the "checkin format" and the individual coder's preferred format.

I've heard of this approach, but I always assumed that it was a
joke.  You really use it?
-- 
"Welcome to the wonderful world of undefined behavior, where the demons
 are nasal and the DeathStation users are nervous." --Daniel Fox
0
Reply blp (3953) 2/26/2010 3:48:06 AM

Keith Thompson wrote:
> John Bode <jfbode1029@gmail.com> writes:
> [...]
>> The all-caps convention makes it easier to distinguish preprocessor
>> macros from other symbols.  This can matter, especially when using
>> function-like macros (macros that take arguments).  Remember that
>> macro expansions are simple text substitutions; a macro like
>>
>> #define square(x) (x*x)
>>
>> does not compute "x*x" and return a value; it *replaces* the text
>> "square(x)" with "(x*x)".  If x is "z++", then the replacement text is
>> "(z++*z++)", which invokes undefined behavior.  If x is "a+b", then
>> the replacement text is "(a+b*a+b)".  By using all-uppercase for
>> macros, it makes it easier to see potential red flags like "SQUARE(x+
>> +)" or "SQUARE(x+y)".
> [...]
> 
> The side effect problem can't be solved (or at least can't be easily
> solved) if you're using a macro, but the operator precedence problem
> can.
> 
> #define SQUARE(x) ((x)*(x))
> 
> You need to parenthesize the entire definition *and* each reference to
> the parameter(s).
> 
> BTW, here's my favorite example of preprocessor abuse:
> 
> #include <stdio.h>
> 
> #define SIX 1+5
> #define NINE 8+1
> 
> int main(void)
> {
>     printf("%d * %d = %d\n", SIX, NINE, SIX * NINE);
>     return 0;
> }
> 

$ gcc -D_GNU_SOURCE -Wall -Wextra k1.c -o out
$ ./out
6 * 9 = 42
$ cat k1.c
#include <stdio.h>

#define SIX 1+5
#define NINE 8+1

int main(void)
{
     printf("%d * %d = %d\n", SIX, NINE, SIX * NINE);
     return 0;
}

// gcc -D_GNU_SOURCE -Wall -Wextra k1.c -o out
$


SIX * NINE equals 1 + 5 * 8 + 1

I save these nice little toy programs in my linuxlog.

-- 
fred
0
Reply Phred4 (88) 2/26/2010 5:05:43 AM

On Thu, 25 Feb 2010 19:48:06 -0800, Ben Pfaff wrote:

> Kelsey Bjarnason <kbjarnason@gmail.com> writes:
> 
>> My take on this has always been to standardize the format "checked in",
>> then use indent or some equivalent, on check in and check out, to
>> convert between the "checkin format" and the individual coder's
>> preferred format.
> 
> I've heard of this approach, but I always assumed that it was a joke. 
> You really use it?

I have, repeatedly, over the years.

The problem with _not_ doing it is that you tend to get a lot of checkins 
where the "diff" is wildly out of sync with what actually got changed, 
particularly if the coder's tools do things such as switching tabs to 
spaces or re-organizing braces, etc, etc, etc, which many tools do.

By using indent or an equivalent on checkin, you ensure a standard format 
going in, such that only "real" changes are recorded, and by using it on 
checkout, you deliver to the coder whatever flavour he's happiest with.

Or, you can skip it on checkout and just let him use whatever tools he 
likes, but I've found delivering to the developer something which he is 
maximally comfortable with, right out of the gate, tends to produce 
maximum productivity and minimum frustration.

'Course, some of that will depend on the repository tools, too.  Some can 
be set to ignore whitespace differences, or to auto-format to a defined 
standard, etc, etc, etc.  Some can't.  It's easier just to do it 
yourself, with indent or equivalent, as part of the check-in/check-out 
procedure.

0
Reply kbjarnason (4583) 2/26/2010 5:15:12 AM

On Feb 25, 11:15=A0pm, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> On Thu, 25 Feb 2010 19:48:06 -0800, Ben Pfaff wrote:
> > Kelsey Bjarnason <kbjarna...@gmail.com> writes:
>
> >> My take on this has always been to standardize the format "checked in"=
,
> >> then use indent or some equivalent, on check in and check out, to
> >> convert between the "checkin format" and the individual coder's
> >> preferred format.
>
> > I've heard of this approach, but I always assumed that it was a joke.
> > You really use it?
>
> I have, repeatedly, over the years.
>
> The problem with _not_ doing it is that you tend to get a lot of checkins
> where the "diff" is wildly out of sync with what actually got changed,
> particularly if the coder's tools do things such as switching tabs to
> spaces or re-organizing braces, etc, etc, etc, which many tools do.
>
> By using indent or an equivalent on checkin, you ensure a standard format
> going in, such that only "real" changes are recorded, and by using it on
> checkout, you deliver to the coder whatever flavour he's happiest with.
>
> Or, you can skip it on checkout and just let him use whatever tools he
> likes, but I've found delivering to the developer something which he is
> maximally comfortable with, right out of the gate, tends to produce
> maximum productivity and minimum frustration.


A problem with that approach is that it will trash any special/careful
formatting that you might use to clarify a complex section of code.
While indent allows you to disable formatting for sections, that's not
an ideal solution in many ways.

On the flip side, some people can't be coerced into clean formatting,
or making an effort to follow the formatting already established for
the module their editing, no matter how much violence you threaten.
Or keeping "use tabs" turned off in their editors.  At times that gets
bad enough that the easiest solution is to go ahead and run indent (or
the equivalent) and live with the damage.

But there's really no excuse - following a formatting style is not
that hard, even if it's not exactly the one you prefer.  Frankly there
is almost no excuse for not follow the existing style when modifying a
program.  Or following the shop standards when creating a new module.
0
Reply robertwessel2 (1339) 2/26/2010 6:17:49 AM

Ben Pfaff wrote:
> Kelsey Bjarnason <kbjarnason@gmail.com> writes:
> 
>> My take on this has always been to standardize the format "checked in", 
>> then use indent or some equivalent, on check in and check out, to convert 
>> between the "checkin format" and the individual coder's preferred format.
> 
> I've heard of this approach, but I always assumed that it was a
> joke.

Really? Why so?

> You really use it?

I can't speak for Kelsey, obviously, but I wouldn't dream of doubting 
him. And I've used it in a couple of places. It works very well.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/26/2010 6:58:59 AM

On 26 Feb, 06:17, "robertwess...@yahoo.com" <robertwess...@yahoo.com>
wrote:
> On Feb 25, 11:15=A0pm, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> > On Thu, 25 Feb 2010 19:48:06 -0800, Ben Pfaff wrote:
> > > Kelsey Bjarnason <kbjarna...@gmail.com> writes:

> > >> My take on this has always been to standardize the format "checked i=
n",
> > >> then use indent or some equivalent, on check in and check out, to
> > >> convert between the "checkin format" and the individual coder's
> > >> preferred format.
>
> > > I've heard of this approach, but I always assumed that it was a joke.
> > > You really use it?

I worked on a project where you couldn't check code in unless it had
been through indent with a specified set of flags. Well you *could*
but it got flagged somewhere. At first I used to indent to my style
(the indent style was a mix of tabs and spaces which I hated) edit and
indent to project style before check in. But it was such a PITA I just
accepted project style in the end. [cue twenty page rant by nilg about
the corporate castration of the programmer]


> > I have, repeatedly, over the years.
>
> > The problem with _not_ doing it is that you tend to get a lot of checki=
ns
> > where the "diff" is wildly out of sync with what actually got changed,

I do a special layout change only checkin if the layout had gone
wildly astray.

> > particularly if the coder's tools do things such as switching tabs to
> > spaces or re-organizing braces, etc, etc, etc, which many tools do.

I think your tools are broken


> > By using indent or an equivalent on checkin, you ensure a standard form=
at
> > going in, such that only "real" changes are recorded, and by using it o=
n
> > checkout, you deliver to the coder whatever flavour he's happiest with.
>
> > Or, you can skip it on checkout and just let him use whatever tools he
> > likes, but I've found delivering to the developer something which he is
> > maximally comfortable with, right out of the gate, tends to produce
> > maximum productivity and minimum frustration.
>
> A problem with that approach is that it will trash any special/careful
> formatting that you might use to clarify a complex section of code.
> While indent allows you to disable formatting for sections, that's not
> an ideal solution in many ways.
>
> On the flip side, some people can't be coerced into clean formatting,
> or making an effort to follow the formatting already established for
> the module their editing, no matter how much violence you threaten.

on the project I was on they simple wouldn't be able to checkin the
code. If they did end-run around *that* they'd run into trouble at
build time.


> Or keeping "use tabs" turned off in their editors. =A0At times that gets
> bad enough that the easiest solution is to go ahead and run indent (or
> the equivalent) and live with the damage.
>
> But there's really no excuse - following a formatting style is not
> that hard, even if it's not exactly the one you prefer. =A0Frankly there
> is almost no excuse for not follow the existing style when modifying a
> program. =A0Or following the shop standards when creating a new module.

apart from some truly hideous layout styles. One guy must have been
told that using blank lines would make his code clearer.

#include <stdio.h>

int main ( void )

{
    int i =3D 99;

    printf ( "%d\n", i );

    return 0;

}

he never used more than one blank line
0
Reply nick_keighley_nospam (4574) 2/26/2010 8:29:05 AM

On 25 Feb, 16:07, Richard Heathfield <r...@see.sig.invalid> wrote:
> BruceS wrote:
> > On Feb 25, 7:33 am, Malcolm McLean <malcolm.mcle...@btinternet.com>
> > wrote:
> >> On Feb 25, 2:12 pm, ralt...@xs4all.nl (Richard Bos) wrote:
>
> >>> Yeah. Those Kernighan and Ritchie guys knew jack shit about C.
> >> As CS Lewis said, the first pot, which would prove its maker a genius
> >> if it were the first pot ever made, would prove him a dunce if it came
> >> after many millenia of pot-making.
>
> > That's a good one; I'll try to remember it.
> > FWIW, the K&R bit was intentional, to make the joke more obvious. =A0No=
t
> > obvious enough for some, but apparently I either overestimated the
> > volume in the ng, or underestimated the mass. =A0My bad.
>
> Is it not possible that you underestimated the gravity of the situation?

likely misjudged the metric of the manifold
0
Reply nick_keighley_nospam (4574) 2/26/2010 8:35:55 AM

On 25 Feb, 16:21, John Bode <jfbode1...@gmail.com> wrote:

> C++ programmers prefer "char* firstName", because the type of the
> *object* "firstName" is char*. =A0Fine, but what about "char
> lastName[20]"? =A0The type of "lastName" is "20-element array of char",
> but we can't write "char[20] lastName".

but no True C++ would use a C-style array!


>=A0Same thing for function
> types. =A0Same thing for pointers to arrays, pointers to functions,
> etc.
0
Reply nick_keighley_nospam (4574) 2/26/2010 8:53:01 AM

[snips]

On Fri, 26 Feb 2010 00:29:05 -0800, Nick Keighley wrote:

>> > particularly if the coder's tools do things such as switching tabs to
>> > spaces or re-organizing braces, etc, etc, etc, which many tools do.
> 
> I think your tools are broken

Why?

I happen to feel most comfortable working in a specific manner.  Tabs are 
tabs, three columns wide.  Braces belong on the next line, under the 
"for" or whatever they're tied to.  A blank separating various things 
which should be separated, but only one, and not needlessly.  Etc, etc, 
etc.

It's my preferred style, using it keeps me focussed on the problem 
instead of figuring out where the other guy's (to me) brain-dead style 
has left the thrice-damned open brace, particularly if he's using the 
likewise thrice-damned "spaces, not tabs" so popular with some folks but 
which plays merry hob with any editor capable of actually handling tabs 
(i.e. anything written in the last 20 years).

There are three approaches one can take to this:

1) Adopt the other guy's standard, no matter how brain dead it may be.

2) Force him (or them) to use your own, obviously superior style.

3) Allow each coder to use their own style, but enforce a consistent 
style for the repository.

I go for three, if only because for some strange reason, other coders 
don't seem to agree that my obviously superior formatting style should be 
adopted as a universal convention for all C code everywhere.

Option 1 ain't even an option.  Let *him* use that brain-dead style if he 
likes, but if I have to use it, I'd sooner quit and go work for Microsoft.

</tongue_in_cheek>

0
Reply kbjarnason (4583) 2/26/2010 9:26:12 AM

On 26/02/2010 02:56, Kelsey Bjarnason wrote:
> On Wed, 24 Feb 2010 22:09:43 +0000, Scott Lurndal wrote:
>
>> James Harris<james.harris.1@googlemail.com>  writes:
>>> On 24 Feb, 20:53, BruceS<bruce...@hotmail.com>  wrote:
>>>
>>> ...
>>>
>>>> I would like to add that, as long as you're trying to use good style,
>>>> for God's sake don't use the wrong indentation style. =A0If you put
>>>> your opening braces on the same line as your conditional, you'll just
>>>> look like a fool in front of your friends and colleagues.
>>>
>>> Snobbish nonsense!
>>>
>>>
>>>
>> Indeed.
>>
>>     if (condition) {
>>
>> is preferred over
>>
>>     if (condition)
>>     {
>
> Not by me, it ain't. :)
>
>> Makes it much more likely that a properly written function will fit on a
>> single page/screen.
>
> And less likely to catch proper vs improper bracing and indentation, when
> the braces don't line up with the indents.
>
>> In 30 years of C programming, no employer or project has used the latter
>> form.
>
> This is one of those cases where there really are legitimate reasons for
> each approach, with the deciding factor being preference.
>
> My take on this has always been to standardize the format "checked in",
> then use indent or some equivalent, on check in and check out, to convert
> between the "checkin format" and the individual coder's preferred format.

My preferred approach is to do like this:

function wiggy ()
      {
      if (cond)
           {
           dostuff;
           }
      else {
           dootherstuff;
           }
      }

This has been my approach ever since I was writing BCPL in the 70s - it 
has the braces lining up so that the matching can be seen easily.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 2/26/2010 12:08:04 PM

On 26/02/2010 09:26, Kelsey Bjarnason wrote:
> [snips]
>
> On Fri, 26 Feb 2010 00:29:05 -0800, Nick Keighley wrote:
>
>>>> particularly if the coder's tools do things such as switching tabs to
>>>> spaces or re-organizing braces, etc, etc, etc, which many tools do.
>>
>> I think your tools are broken
>
> Why?
>
> I happen to feel most comfortable working in a specific manner.  Tabs are
> tabs, three columns wide.  Braces belong on the next line, under the
> "for" or whatever they're tied to.  A blank separating various things
> which should be separated, but only one, and not needlessly.  Etc, etc,
> etc.
>
> It's my preferred style, using it keeps me focussed on the problem
> instead of figuring out where the other guy's (to me) brain-dead style
> has left the thrice-damned open brace, particularly if he's using the
> likewise thrice-damned "spaces, not tabs" so popular with some folks but
> which plays merry hob with any editor capable of actually handling tabs
> (i.e. anything written in the last 20 years).

Trouble with tabs is, what is a tab? I use the tab key but my editor 
(TextWrangler) just converts them to spaces. Why should spaces bother an 
editor, anyway?

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 2/26/2010 12:29:13 PM

On Thu, 25 Feb 2010 06:37:18 -0800 (PST),
    Anand Hariharan <mailto.anand.hariharan@gmail.com> wrote:
> On Feb 24, 4:09�pm, sc...@slp53.sl.home (Scott Lurndal) wrote:
>>
>> � �if (condition) {
>>
>> is preferred over
>>
>> � �if (condition)
>> � �{
>>
>> Makes it much more likely that a properly written function will fit on a single
>> page/screen.
>>
>> In 30 years of C programming, no employer or project has used the latter form.
>>
>> scott
>
>
> You've gotten some strong reactions to your not-seen-in-30-years
> comment above.
>
> FWIW I use the latter form myself.  However, one good reason I got
> from an ex-colleague for using the first style was that if you are
> scrolling upward in source code, and get to the closing brace of a
> block, using the keyboard shortcut in your editor for jumping to the
> matching brace will get you to see the if (or while or for)
> condition.  Otherwise, it will only scroll upward to a point where the
> opening brace is shown as the first line, and one has to go up one
> line more.  To me, this is not a big inconvenience.
>
However, the converse is that when cursoring down the code you have to:

a) watch the RH edge of the code for the brace and watch for when the
cursor is on the same line but in column 1 - this is especially true if
you've just bounced to a '}' previously because, at least in vim, you
then lose the "end of line" behaviour of the cursor and it retains the
column position.

b) At least for vim you have to then do $ to get to the end of the line
before you hit the % to find the matching close brace.

   if(x<0) {
   }
Hitting % while in column 1 of the if line in vim bounces you between
the '(' and ')'

   if(x<0)
   {
   }
Hitting % while in column 1 (or any column) of the line with '{' bounces
you to the '}'

c) Assuming the code is correctly indented - starting with your cursor
on the '{' and then moving downwards you will have read the entire block
when the cursor first stops on a '}' (Assuming your cursor isn't
following the end of the line)

d) For people who persist on using long lines, putting the '{' on a line
on its own will mean it is not off the edge of the screen and invisible
or wrapped onto the next line

Obviously, the major advantage to putting the '{' on the same line as
the conditional is that it reduces paper usage when typesetting and
hence why you will normally see it in books.

Tim.



-- 
God said, "div D = rho, div B = 0, curl E = - @B/@t, curl H = J + @D/@t," 
and there was light.

  http://www.woodall.me.uk/
0
Reply devnull13 (45) 2/26/2010 1:16:23 PM

Tim Streater wrote:
<snip>

> Trouble with tabs is, what is a tab?

A quick way of inserting exactly two spaces into the source.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/26/2010 2:51:16 PM

On 26/02/2010 14:51, Richard Heathfield wrote:
> Tim Streater wrote:
> <snip>
>
>> Trouble with tabs is, what is a tab?
>
> A quick way of inserting exactly two spaces into the source.

Since I don't know what tab setting you had when you handed me the code, 
I think s/exactly two/a random number of/ applies here.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 2/26/2010 3:12:02 PM

Tim Streater wrote:
> On 26/02/2010 14:51, Richard Heathfield wrote:
>> Tim Streater wrote:
>> <snip>
>>
>>> Trouble with tabs is, what is a tab?
>>
>> A quick way of inserting exactly two spaces into the source.
> 
> Since I don't know what tab setting you had when you handed me the code,

It doesn't matter, since all you get is spaces. (Well, hopefully you get 
some code in between the white spaces, too...)

> I think s/exactly two/a random number of/ applies here.

No, exactly two. Always. It's the One True Tab Size. And if you 
disagree, obviously you're not a real Scotsman.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/26/2010 3:23:37 PM

Richard Heathfield  wrote in message
<FqmdncxYjq_tehrWnZ2dnUVZ7t5i4p2d@bt.com>:
> No, exactly two. Always. It's the One True Tab Size.

Would you be interested in a keyboard that, instead of the space bar, has
six standard-sized keys that insert respectively 0, 1, 2, 3, 4 and 5 spaces?
0
Reply george54 (194) 2/26/2010 3:49:53 PM

On 2010-02-26, Nicolas George <nicolas$george@salle-s.org> wrote:
> Richard Heathfield  wrote in message
><FqmdncxYjq_tehrWnZ2dnUVZ7t5i4p2d@bt.com>:
>> No, exactly two. Always. It's the One True Tab Size.
>
> Would you be interested in a keyboard that, instead of the space bar, has
> six standard-sized keys that insert respectively 0, 1, 2, 3, 4 and 5 spaces?

Think how futuristic you would feel to tell people, your
keyboard has a "space-pad" in addition to the numpad.


-- 
Andrew Poelstra
http://www.wpsoftware.net/andrew
0
Reply apoelstra (387) 2/26/2010 4:41:02 PM

On 26/02/2010 15:23, Richard Heathfield wrote:
> Tim Streater wrote:
>> On 26/02/2010 14:51, Richard Heathfield wrote:
>>> Tim Streater wrote:
>>> <snip>
>>>
>>>> Trouble with tabs is, what is a tab?
>>>
>>> A quick way of inserting exactly two spaces into the source.
>>
>> Since I don't know what tab setting you had when you handed me the code,
>
> It doesn't matter, since all you get is spaces. (Well, hopefully you get
> some code in between the white spaces, too...)
>
>> I think s/exactly two/a random number of/ applies here.
>
> No, exactly two. Always. It's the One True Tab Size. And if you
> disagree, obviously you're not a real Scotsman.

<innocent look>
You mean they tend to cheesepare?
</innocent>

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 2/26/2010 5:51:32 PM

Kelsey Bjarnason <kbjarnason@gmail.com> writes:

> On Thu, 25 Feb 2010 19:48:06 -0800, Ben Pfaff wrote:
>
>> Kelsey Bjarnason <kbjarnason@gmail.com> writes:
>> 
>>> My take on this has always been to standardize the format "checked in",
>>> then use indent or some equivalent, on check in and check out, to
>>> convert between the "checkin format" and the individual coder's
>>> preferred format.
>> 
>> I've heard of this approach, but I always assumed that it was a joke. 
>> You really use it?
>
> I have, repeatedly, over the years.
>
> The problem with _not_ doing it is that you tend to get a lot of checkins 
> where the "diff" is wildly out of sync with what actually got changed, 
> particularly if the coder's tools do things such as switching tabs to 
> spaces or re-organizing braces, etc, etc, etc, which many tools do.

I've never seen widespread problems with that.  When I do, I see
folks deal with it by telling the coder in question not to screw
stuff up.

Do any open source or free software projects work this way?  I am
familiar with many, and I've never seen anything like this.

(Doesn't it take *forever* to reformat a large source tree, by
the way?  It took a few minutes here just to run "wc" on the .c
files in a Linux kernel tree, and I imagine that "indent" is
slower than "wc".)

> By using indent or an equivalent on checkin, you ensure a standard format 
> going in, such that only "real" changes are recorded, and by using it on 
> checkout, you deliver to the coder whatever flavour he's happiest with.

Doesn't it screw up any careful formatting, e.g. of comments?
And sometimes careful placement of white space can make the code
much easier to read.
-- 
"Some programming practices beg for errors;
 this one is like calling an 800 number
 and having errors delivered to your door."
--Steve McConnell
0
Reply blp (3953) 2/26/2010 5:53:42 PM

Richard Heathfield <rjh@see.sig.invalid> writes:

> Ben Pfaff wrote:
>> Kelsey Bjarnason <kbjarnason@gmail.com> writes:
>>
>>> My take on this has always been to standardize the format "checked
>>> in", then use indent or some equivalent, on check in and check out,
>>> to convert between the "checkin format" and the individual coder's
>>> preferred format.
>>
>> I've heard of this approach, but I always assumed that it was a
>> joke.
>
> Really? Why so?

Because I've looked at many, many software projects and worked on
several and I've never seen this approach actually used.
-- 
"Structure padding is the use of extraneous materials to
 enhance the shape of a struct and make it more attractive to
 members of the opposite struct.  (See also "struct silicone.")"
--Eric Sosman
0
Reply blp (3953) 2/26/2010 5:54:27 PM

Keith Thompson <kst-u@mib.org> writes:

> Stephen Sprunk <stephen@sprunk.org> writes:
>> On 24 Feb 2010 12:35, Poster Matt wrote:
> [...]
>>> EG:
>>> Variables: int numFiles = 0;
>>
>> This is camelCase.
>>
>>> Functions: int CountNumFilesInDir(char* path);
>>
>> This is PascalCase.
>>
>> Mixing the two in the same project will drive adherents of _both_ styles
>> nuts.  Pick one and stick to it; that way you'll only drive half of your
>> readers nuts.
>
> His convention apparently is to use camelCase for variables and
> PascalCase for functions.  It's not necessarily a style I'd use, but
> it's not obviously horrible (and it's more or less the style I use
> at work).  As with most of these rules, conforming to existing code
> is far more important than any benefits of one style over another.
> I really dislike the brace placement of the code I work on, but
> mixing my own style into it would be far worse (and wouldn't survive
> a code review anyway).
>
>> (There's also this_type_of_identifier; the same logic applies, i.e.
>> don't mix that with either of the above.  Never, never create some
>> God-awful hybrid with both underscores and uppercase letters...)
>
> Again, This_Type_Of_Identifier isn't obviously horrible.  (I use it
> myself, though not in C.)

I confess to using lower_case_like_this for variables, and
Initial_Capitals like that for functions.  It does help when you see
run_this() and know you don't have to go looking for the prototype.
-- 
Online waterways route planner            | http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
0
Reply 3-nospam (285) 2/26/2010 6:51:55 PM

raltbos@xs4all.nl (Richard Bos) writes:

> Seebs <usenet-nospam@seebs.net> wrote:
>
>> On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>> > 5. On a slightly different note, I've been handling my error messages by using 
>> > #define string constants in a header file. I saw some code which did this and it 
>> > looked good to me. Is that standard practise, if not what is?
>> 
>> > EG. #define ErrorDirNotFound "The directory was not found."
>> 
>> No.  Look into gettext() if you need to do this, or just put them in
>> literally.
>
> gettext() is nice if you have it (it's POSIX, isn't it? Not ISO, anyway,
> but common), but putting the messages in literally only works if you
> don't reuse them. IME, _some_ error messages are used more than once, in
> which case a #define is nice.

I create an enum for errors, and a table of messages (by using something
like this):
ERCODE(err_signal,"A Signal was trapped")
ERCODE(err_internal,"Something went wrong internal to the interpreter")
ERCODE(err_failure,"An operating system function failed")
ERCODE(err_memory,"Ran out of memory")  // keep this as the last of the prog kil
lers
ERCODE(err_unimp,"This is not yet implemented")
ERCODE(err_syntax,"Syntax error")
ERCODE(err_open,"Error with file")
ERCODE(err_mismatch,"Mismatched types")
ERCODE(err_killed,"Program told to stop")
ERCODE(err_locking,"Database locking failed")
ERCODE(err_cs,"Error reported by ClearSilver templating system")

and a bit of #define magic, you can create the enum and the table
indexed by it in one go.

Oh, and I've just realised that this is non-conforming code.  I probably
better start my error code macro with a P or something.
-- 
Online waterways route planner            | http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
0
Reply 3-nospam (285) 2/26/2010 6:56:01 PM

Richard Heathfield <rjh@see.sig.invalid> writes:
> Tim Streater wrote:
> <snip>
>
>> Trouble with tabs is, what is a tab?
>
> A quick way of inserting exactly two spaces into the source.

The One True Tabstop Width is 8.

I have to deal with code that was modified by multiple different
people.  Most of them use a tabstop width of 4, but some apparently
use 2, 8, or something else, resulting in code that's not properly
formatted regardless of my own tabstop setting.

Everything I check in has its tabs expanded to spaces.  (I use
"expand -t 4" with manual cleanup where necessary.)

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/26/2010 7:28:19 PM

In article <lnmxyvvlt8.fsf@nuthaus.mib.org>,
Keith Thompson  <kst-u@mib.org> wrote:
>Richard Heathfield <rjh@see.sig.invalid> writes:

>>> Trouble with tabs is, what is a tab?

>> A quick way of inserting exactly two spaces into the source.

>The One True Tabstop Width is 8.
>
>I have to deal with code that was modified by multiple different
>people.  Most of them use a tabstop width of 4, but some apparently
>use 2, 8, or something else, resulting in code that's not properly
>formatted regardless of my own tabstop setting.

I think Richard H was referring to the effect of the tab key in an
editor, rather than the display of a tab character.

For example, I have the tab key set to indent 4 spaces; if I do
that twice I get a tab character which then displays as 8 spaces.

>Everything I check in has its tabs expanded to spaces.

Now that the overhead is (and has long been) unimportant, that's
probably a good idea.

-- Richard
-- 
Please remember to mention me / in tapes you leave behind.
0
Reply richard91 (3683) 2/26/2010 7:37:25 PM

>
>
> [...] when cursoring down the code [...]
>
The next step in this merry little dance, danced so many times before, 
is to point out the existence of folding text editors.  Well done for 
bringing the editor wars into the thread, though.  That will make it 
even larger.  Now all you need is some way to bring the operating system 
and browser wars in, as well.  Obviously the earlier mentions of NetBSD 
didn't take.

How about this

"Well we all know what coding styles were used to write ReactOS and 
Google Chrome.  And just look at the results!"

?  (-:

0
Reply J.deBoynePollard-newsgroups (95) 2/26/2010 8:56:32 PM

On 26 Feb, 19:28, Keith Thompson <ks...@mib.org> wrote:
> Richard Heathfield <r...@see.sig.invalid> writes:
> > Tim Streater wrote:
> > <snip>
>
> >> Trouble with tabs is, what is a tab?
>
> > A quick way of inserting exactly two spaces into the source.
>
> The One True Tabstop Width is 8.
>
> I have to deal with code that was modified by multiple different
> people. =A0Most of them use a tabstop width of 4, but some apparently
> use 2, 8, or something else, resulting in code that's not properly
> formatted regardless of my own tabstop setting.
>
> Everything I check in has its tabs expanded to spaces. =A0(I use
> "expand -t 4" with manual cleanup where necessary.)

For anything outside Unix or Linux others may find the following tabs
expander and compressor useful

  http://codewiki.wikispaces.com/tabs.py

It allows arbitrary and/or repeating tab stop positions and obeys they
usual Unix pipe arrangements. Examples of use are included on the
page.

Although it doesn't require Unix be aware that it does need Python.
I've not tested it under Python 3.x but it works ok under Python 2.x.

James
0
Reply james.harris.1 (384) 2/26/2010 9:30:41 PM

Richard Heathfield wrote:
> 
> Tim Streater wrote:
> <snip>
> 
> > Trouble with tabs is, what is a tab?
> 
> A quick way of inserting exactly two spaces into the source.

FOUR SPACES!!!

-- 
pete
0
Reply pfiland (6613) 2/26/2010 10:25:14 PM

On 2/26/2010 9:51 AM, Richard Heathfield wrote:
> Tim Streater wrote:
> <snip>
>
>> Trouble with tabs is, what is a tab?
>
> A quick way of inserting exactly two spaces into the source.

     The only actual study I ever read of (that's "read of," as
in "I didn't read it myself and can't cite it") found that the
best tab spacing was greater than two and less than four.  Even
without further experiment, it's blatantly obvious that these
lower and upper bounds bracket the Best Possible Tab Width, to
wit, pi spaces.  This is easily approximated by making the tab
key operate probabilistically, advancing to a three- or four-
space position with probabilities 0.142 and 0.858, respectively.
(If you need a more accurate approximation to the fractional
part of pi, your lines are too long.)

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Reply esosman2 (2945) 2/26/2010 10:45:17 PM

On 2/26/2010 5:45 PM, Eric Sosman wrote:
> [...] pi spaces. This is easily approximated by making the tab
> key operate probabilistically, advancing to a three- or four-
> space position with probabilities 0.142 and 0.858, respectively.
> [...]

     You've heard of "fencepost errors?"  This is a "newspost error."

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Reply esosman2 (2945) 2/26/2010 10:49:28 PM

Keith Thompson wrote:
> Richard Heathfield <rjh@see.sig.invalid> writes:
>> Tim Streater wrote:
>> <snip>
>>
>>> Trouble with tabs is, what is a tab?
>> A quick way of inserting exactly two spaces into the source.
> 
> The One True Tabstop Width is 8.

You, sirrah, are no Scotsman!

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/26/2010 11:03:38 PM

On 26 Feb 2010 11:53, Ben Pfaff wrote:
> (Doesn't it take *forever* to reformat a large source tree, by
> the way?  It took a few minutes here just to run "wc" on the .c
> files in a Linux kernel tree, and I imagine that "indent" is
> slower than "wc".)

Last time I checked, the vast majority of wc's runtime was opening,
reading, and closing files, i.e. the parts that make the disk's head
skip all over the place, not actually counting lines.  indent does a
little bit more with the data than wc does, but on a tolerably fast
machine I suspect that the extra work would just fill in (a few of) the
CPU cycles wc wastes while waiting for the disk...

S

-- 
Stephen Sprunk         "God does not play dice."  --Albert Einstein
CCIE #3723         "God is an inveterate gambler, and He throws the
K5SSS        dice at every possible opportunity." --Stephen Hawking
0
Reply stephen (1122) 2/26/2010 11:11:27 PM

On 26 Feb 2010 09:12, Tim Streater wrote:
> On 26/02/2010 14:51, Richard Heathfield wrote:
>> Tim Streater wrote:
>>> Trouble with tabs is, what is a tab?
>>
>> A quick way of inserting exactly two spaces into the source.
> 
> Since I don't know what tab setting you had when you handed me the code,
> I think s/exactly two/a random number of/ applies here.

That's a problem with _mixing tabs and spaces_, which is Evil(tm).

If you use a tab character (inserted by pressing the tab key) for each
level of indentation, each programmer can set the tab stops in his
editor however he wants and it will look correct for everyone.

(That introduces a new problem if you want to limit to 80 columns, but
that can be remedied by saying "80 columns with X-character tabs".)

S

-- 
Stephen Sprunk         "God does not play dice."  --Albert Einstein
CCIE #3723         "God is an inveterate gambler, and He throws the
K5SSS        dice at every possible opportunity." --Stephen Hawking
0
Reply stephen (1122) 2/26/2010 11:16:21 PM

Julienne Walker <happyfrosty@hotmail.com> writes:
>> 4. Does anyone care where the pointer * is? I prefer keeping to next to the
>> type, rather than next to the variable name.
>>
>> EG. I like: char* firstName; and not so much: char *firstName;
>
> Just make sure you're consistent and nobody will care. :-)

Horrifically wrong. Just make sure you're consistent with everyone
else, and nobody will care.

Phil
0
Reply thefatphil_demunged (1558) 2/26/2010 11:26:29 PM

Ian Collins <ian-news@hotmail.com> writes:
> Scott Lurndal wrote:
>> James Harris <james.harris.1@googlemail.com> writes:
>>> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>> ...
>>>> I would like to add that, as long as you're trying to use good style,
>>>> for God's sake don't use the wrong indentation style. =A0If you put your
>>>> opening braces on the same line as your conditional, you'll just look
>>>> like a fool in front of your friends and colleagues.
>>> Snobbish nonsense!
>>
>> Indeed.
>>
>>    if (condition) {
>>
>> is preferred over
>>
>>    if (condition)
>>    {
>
> By whom?

Our Lord and Master, Linux Fucking Torvalds!

Documentation/CodingStyle

Read it and weep.

Phil
-- 
I find the easiest thing to do is to k/f myself and just troll away
-- David Melville on r.a.s.f1
0
Reply thefatphil_demunged (1558) 2/26/2010 11:39:36 PM

Phil Carmody <thefatphil_demunged@yahoo.co.uk> writes:

> Ian Collins <ian-news@hotmail.com> writes:
>> Scott Lurndal wrote:
>>> James Harris <james.harris.1@googlemail.com> writes:
>>>> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>>> ...
>>>>> I would like to add that, as long as you're trying to use good style,
>>>>> for God's sake don't use the wrong indentation style. =A0If you put your
>>>>> opening braces on the same line as your conditional, you'll just look
>>>>> like a fool in front of your friends and colleagues.
>>>> Snobbish nonsense!
>>>
>>> Indeed.
>>>
>>>    if (condition) {
>>>
>>> is preferred over
>>>
>>>    if (condition)
>>>    {
>>
>> By whom?
>
> Our Lord and Master, Linux Fucking Torvalds!

And K&R

And for a damn good reason.

But good to see you continuing to insult your betters.

>
> Documentation/CodingStyle
>
> Read it and weep.
>
> Phil

It is ludocrous to recommend the second form. ALL it does is waste a
line. Indentation is there for a reason. We dont need to see the opening
bracket on its own wasted line.

,----
| int func(int p){
|     a;
|     b;
|     c;
| }
`----

is superior to 

,----
| int func(int p)
| {
|     a;
|     b;
|     c;
| }
`----

because it does the same thing in one line less with ZERO reduction in
readability.

-- 
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c
0
Reply rgrdev_ (1087) 2/26/2010 11:54:08 PM

Jonathan de Boyne Pollard wrote:
<snip>
>> [...] Well done for 
> bringing the editor wars into the thread, though.  That will make it 
> even larger.  Now all you need is some way to bring the operating system 
> and browser wars in, as well.

Under what category would we place emacs, I wonder? :-)

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/26/2010 11:59:11 PM

On Feb 26, 5:11=A0pm, Stephen Sprunk <step...@sprunk.org> wrote:
> On 26 Feb 2010 11:53, Ben Pfaff wrote:
>
> > (Doesn't it take *forever* to reformat a large source tree, by
> > the way? =A0It took a few minutes here just to run "wc" on the .c
> > files in a Linux kernel tree, and I imagine that "indent" is
> > slower than "wc".)
>
> Last time I checked, the vast majority of wc's runtime was opening,
> reading, and closing files, i.e. the parts that make the disk's head
> skip all over the place, not actually counting lines. =A0indent does a
> little bit more with the data than wc does, but on a tolerably fast
> machine I suspect that the extra work would just fill in (a few of) the
> CPU cycles wc wastes while waiting for the disk...
>
> S
>

indent would have to /write/ the files to the disk, but wc does not.
0
Reply mailto.anand.hariharan (147) 2/27/2010 12:31:37 AM

In article <hm9j5p$u88$2@news.eternal-september.org>, Eric Sosman <esosman@ieee-dot-org.invalid> writes:
> On 2/26/2010 5:45 PM, Eric Sosman wrote:
>> [...] pi spaces. This is easily approximated by making the tab
>> key operate probabilistically, advancing to a three- or four-
>> space position with probabilities 0.142 and 0.858, respectively.
>> [...]
> 
>      You've heard of "fencepost errors?"  This is a "newspost error."

(I'm going out on a limb here.)

Do you mean you reversed the order of probabilities (relative
frequencies)?

E(spc_per_tab) = E(3 + X) = 3 + E(X) = 3 + (0 * 0.858 + 1 * 0.142) 

You also wrote:

> (If you need a more accurate approximation to the fractional
> part of pi, your lines are too long.)

Having a large number of tabs is also possible by having many lines in a
file, or many files in a project :)

Cheers,
lacos
0
Reply lacos (176) 2/27/2010 1:00:22 AM

Richard wrote:
> Phil Carmody <thefatphil_demunged@yahoo.co.uk> writes:
> 
>> Ian Collins <ian-news@hotmail.com> writes:
>>> Scott Lurndal wrote:
>>>> James Harris <james.harris.1@googlemail.com> writes:
>>>>> On 24 Feb, 20:53, BruceS <bruce...@hotmail.com> wrote:
>>>>> ...
>>>>>> I would like to add that, as long as you're trying to use good style,
>>>>>> for God's sake don't use the wrong indentation style. =A0If you put your
>>>>>> opening braces on the same line as your conditional, you'll just look
>>>>>> like a fool in front of your friends and colleagues.
>>>>> Snobbish nonsense!
>>>> Indeed.
>>>>
>>>>    if (condition) {
>>>>
>>>> is preferred over
>>>>
>>>>    if (condition)
>>>>    {
>>> By whom?
>> Our Lord and Master, Linux Fucking Torvalds!
> 
> And K&R
> 
> And for a damn good reason.

Yes, to save space in a book.

> But good to see you continuing to insult your betters.
> 
>> Documentation/CodingStyle
>>
>> Read it and weep.
> 
> It is ludocrous to recommend the second form. ALL it does is waste a
> line. Indentation is there for a reason. We dont need to see the opening
> bracket on its own wasted line.

What's the going rate for a line these days?

-- 
Ian Collins
0
Reply ian-news (9878) 2/27/2010 1:07:28 AM

On Feb 26, 8:31=A0pm, Anand Hariharan <mailto.anand.hariha...@gmail.com>
wrote:
> On Feb 26, 5:11=A0pm, Stephen Sprunk <step...@sprunk.org> wrote:
>
>
>
> > On 26 Feb 2010 11:53, Ben Pfaff wrote:
>
> > > (Doesn't it take *forever* to reformat a large source tree, by
> > > the way? =A0It took a few minutes here just to run "wc" on the .c
> > > files in a Linux kernel tree, and I imagine that "indent" is
> > > slower than "wc".)
>
> > Last time I checked, the vast majority of wc's runtime was opening,
> > reading, and closing files, i.e. the parts that make the disk's head
> > skip all over the place, not actually counting lines. =A0indent does a
> > little bit more with the data than wc does, but on a tolerably fast
> > machine I suspect that the extra work would just fill in (a few of) the
> > CPU cycles wc wastes while waiting for the disk...
>
> > S
>
> indent would have to /write/ the files to the disk, but wc does not.

Which might not take any appreciable extra time, depending on
(among other things) seek vs read vs write time,
disk fragementation and buffering strategies.

                     - William Hughes

0
Reply wpihughes (390) 2/27/2010 1:10:07 AM

In article <2i3m57-tcp.ln1@news.eternal-september.org>,
Richard  <rgrdev_@gmail.com> wrote:
>It is ludocrous to recommend the second form. ALL it does is waste a
>line. Indentation is there for a reason. We dont need to see the opening
>bracket on its own wasted line.

Are you not also "wasting a line" for the closing brace?
Is that ludicrous too?
Why do you need to see the closing brace on its own line, but not the
opening brace? Doesn't that destroy the symmetry?

Then, it's not always black and white.
Consider the case where a condition does not fit on a single line:

    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
        needs_processing(color)) {
        compute_volume(length, width, height);
        compute_something_else(price, weight);
    }

vs.

    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
        needs_processing(color))
    {
        compute_volume(length, width, height);
        compute_something_else(price, weight);
    }

In the first case, it is hard to see where the condition ends
and where the body starts. In the second case it's obvious.
Don't you think that the opening brace on its own line here improves
the readability?
0
Reply ike5 (222) 2/27/2010 2:10:14 AM

Ian Collins wrote:
> Richard wrote:
<snip>

>> It is ludocrous to recommend the second form. ALL it does is waste a
>> line. Indentation is there for a reason. We dont need to see the opening
>> bracket on its own wasted line.
> 
> What's the going rate for a line these days?

People should avoid trying to answer that question until they have 
checked their answer in the debugger.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/27/2010 4:10:32 AM

Ike Naar wrote:
> 
> In article <2i3m57-tcp.ln1@news.eternal-september.org>,
> Richard  <rgrdev_@gmail.com> wrote:
> >It is ludocrous to recommend the second form. ALL it does is waste a
> >line. Indentation is there for a reason. We dont need to see the opening
> >bracket on its own wasted line.
> 
> Are you not also "wasting a line" for the closing brace?
> Is that ludicrous too?
> Why do you need to see the closing brace on its own line, but not the
> opening brace? Doesn't that destroy the symmetry?
> 
> Then, it's not always black and white.
> Consider the case where a condition does not fit on a single line:
> 
>     if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>         sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>         needs_processing(color)) {
>         compute_volume(length, width, height);
>         compute_something_else(price, weight);
>     }
> 
> vs.
> 
>     if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>         sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>         needs_processing(color))
>     {
>         compute_volume(length, width, height);
>         compute_something_else(price, weight);
>     }
> 
> In the first case, it is hard to see where the condition ends
> and where the body starts. In the second case it's obvious.
> Don't you think that the opening brace on its own line here improves
> the readability?

Yes, but only in that case.
That's a special case under Indian Hill C Style and Coding Standards .

http://www.psgd.org/paul/docs/cstyle/cstyle06.htm

-- 
pete
0
Reply pfiland (6613) 2/27/2010 4:17:02 AM

In comp.lang.c Ike Naar <ike@localhost.claranet.nl> wrote:
<snip>
> Consider the case where a condition does not fit on a single line:
>
>     if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>         sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>         needs_processing(color)) {
>         compute_volume(length, width, height);
>         compute_something_else(price, weight);
>     }

I agree that that's a sore spot. But in complex conditions I often like to
align the logical operators w/ the if statement.

    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3
    &&  sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3
    &&  needs_processing(color)) {
        compute_volume(length, width, height);
        compute_something_else(price, weight);
    }

Along with 8 space aligned indentation, it's not that bad.

0
Reply William 2/27/2010 5:19:25 AM

[snips]

On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:

> Trouble with tabs is, what is a tab?

It's a character, often ASCII 9, which tells your editor to indent (or, 
on removal, unindent) by whatever number of columns is required to bring 
things in line with the next (previous) tab stop.

Contrast that to hitting delete on a line which uses spaces instead of 
tabs.  All this does is mess up the formatting, as the editor is almost 
certain to treat a space as a _space_, as it should, not as a tab, which 
it _shouldn't_, because the character involved is not a tab, but a space.

Then, of course, there's inserting.  Hit space.  See how many columns the 
line indents.  One, isn't it?  Why is that?  Oh, yes, because spaces 
aren't tabs, and editors won't treat them as tabs.  Tabs are tabs, and 
editors treat them that way.

AFAIK, even Emacs and vi can cope with tabs.  I've yet to meet _any_ 
editor which, when you delete a space, correctly determines that you 
really meant to delete four spaces, and removes that many, or, when you 
hit the spacebar, correctly figures out that you actually meant a tab, 
not a space, and thus inserts 4 (or is it 3?  8?  5?) spaces.

> I use the tab key but my editor
> (TextWrangler) just converts them to spaces. Why should spaces bother an
> editor, anyway?

Because spaces, for purposes of indentation, are defective by design, and 
editors are generally built in such a manner as to use the right thing 
for the right job.  Spaces between words, etc, tabs for indentation.

0
Reply kbjarnason (4583) 2/27/2010 5:32:05 AM

On Fri, 26 Feb 2010 11:28:19 -0800, Keith Thompson wrote:

> Richard Heathfield <rjh@see.sig.invalid> writes:
>> Tim Streater wrote:
>> <snip>
>>
>>> Trouble with tabs is, what is a tab?
>>
>> A quick way of inserting exactly two spaces into the source.
> 
> The One True Tabstop Width is 8.

Three, actually.  Okay, 8, if you're stuck using output devices from the 
1960's which didn't allow user-defined tab spaces, but for how many 
people is this true anymore?

> I have to deal with code that was modified by multiple different people.
>  Most of them use a tabstop width of 4, but some apparently use 2, 8, or
> something else, resulting in code that's not properly formatted
> regardless of my own tabstop setting.

Now imagine if they were using spaces.  This guy uses two, the next guy 
uses three, the third guy uses 4, the fourth guy uses 5, some other guy 
uses 8.

With tabs, at least just by setting your tab stops, you can get a degree 
of consistency.  Have fun sorting out the nightmare of inconsistency 
spaces lead to.

0
Reply kbjarnason (4583) 2/27/2010 5:36:38 AM

Kelsey Bjarnason <kbjarnason@gmail.com> writes:

> [snips]
>
> On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:
>
>> Trouble with tabs is, what is a tab?
>
> It's a character, often ASCII 9, which tells your editor to indent (or, 
> on removal, unindent) by whatever number of columns is required to bring 
> things in line with the next (previous) tab stop.

Something tells me Tim might have know that.

>
> Contrast that to hitting delete on a line which uses spaces instead of 
> tabs.  All this does is mess up the formatting, as the editor is almost 
> certain to treat a space as a _space_, as it should, not as a tab, which 
> it _shouldn't_, because the character involved is not a tab, but a
> space.

Not with any half competent editor.

>
> Then, of course, there's inserting.  Hit space.  See how many columns the 
> line indents.  One, isn't it?  Why is that?  Oh, yes, because spaces 
> aren't tabs, and editors won't treat them as tabs.  Tabs are tabs, and 
> editors treat them that way.

And often treat spaces as tabs too. press left or right or delete on y
white space area and it deletes to a tap stop.

>
> AFAIK, even Emacs and vi can cope with tabs.  I've yet to meet _any_ 

Even? Emacs is probably the most advanced editor out there. And vi one
of the most popular programmers editor.

> editor which, when you delete a space, correctly determines that you 
> really meant to delete four spaces, and removes that many, or, when you 
> hit the spacebar, correctly figures out that you actually meant a tab, 
> not a space, and thus inserts 4 (or is it 3?  8?  5?) spaces.
>
>> I use the tab key but my editor
>> (TextWrangler) just converts them to spaces. Why should spaces bother an
>> editor, anyway?

They don't if you're half competent and configure it properly.

>
> Because spaces, for purposes of indentation, are defective by design,
> and 

What total bullshit. Most people use spaces for indentation.

> editors are generally built in such a manner as to use the right thing 
> for the right job.  Spaces between words, etc, tabs for indentation.
>

Totally and utterly wrong. Its rare to find tabs used anymore. Most
editors are LSEs (language sensitive editors) and indent automatically
based on a configured language layout.

-- 
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c
0
Reply rgrdev_ (1087) 2/27/2010 6:00:50 AM

Tim Streater <timstreater@waitrose.com> writes:

> Trouble with tabs is, what is a tab?

<URL:http://www.jwz.org/doc/tabs-vs-spaces.html>
<URL:http://c2.com/cgi/wiki?TabsVersusSpaces>
<URL:http://www.codinghorror.com/blog/archives/001254.html>

-- 
 \             “The greater the artist, the greater the doubt; perfect |
  `\       confidence is granted to the less talented as a consolation |
_o__)                                           prize.” —Robert Hughes |
Ben Finney
0
Reply unix49 (48) 2/27/2010 8:32:07 AM

On 27 Feb, 05:36, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> On Fri, 26 Feb 2010 11:28:19 -0800, Keith Thompson wrote:
> > Richard Heathfield <r...@see.sig.invalid> writes:
> >> Tim Streater wrote:
> >> <snip>
>
> >>> Trouble with tabs is, what is a tab?
>
> >> A quick way of inserting exactly two spaces into the source.
>
> > The One True Tabstop Width is 8.
>
> Three, actually. =A0Okay, 8, if you're stuck using output devices from th=
e
> 1960's which didn't allow user-defined tab spaces, but for how many
> people is this true anymore?

Windows Notepad users are stuck with 8. Windows Wordpad users seem to
be stuck with 6. These are not earlier than the 1980s.

Come to think of it, apart from those two programs what do Windows
users use to enter and edit source code?

I don't think I ever use tabs when typing a high level language. I
always use spaces - just two per indent. Then there are no portability
problems, except for the line ends, of course, and they can be ignored
or dealt with.

IMHO embedded tabs in source code should be consigned to the wastebin
of history as just one of those non-printable characters we used to
hate. Why? Well, they generate a different result depending on where
they are placed and *look like* something else - i.e. one or more
spaces. They are, to an extent, hidden.

Older ones among us may remember dealing with invisible control
characters. For example, moving the cursor across a line one character
at a time looking for where it didn't move. That showed where the
invisible character was embedded. Not fun.

James
0
Reply james.harris.1 (384) 2/27/2010 8:39:29 AM

On 27 Feb, 05:19, William Ahern <will...@wilbur.25thandClement.com>
wrote:
> In comp.lang.c Ike Naar <i...@localhost.claranet.nl> wrote:
> <snip>
>
> > Consider the case where a condition does not fit on a single line:
>
> > =A0 =A0 if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) =
=3D=3D 3 &&
> > =A0 =A0 =A0 =A0 sscanf(other_buffer, "%d %d %d", &color, &price, &weigh=
t) =3D=3D 3 &&
> > =A0 =A0 =A0 =A0 needs_processing(color)) {
> > =A0 =A0 =A0 =A0 compute_volume(length, width, height);
> > =A0 =A0 =A0 =A0 compute_something_else(price, weight);
> > =A0 =A0 }
>
> I agree that that's a sore spot. But in complex conditions I often like t=
o
> align the logical operators w/ the if statement.
>
> =A0 =A0 if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) =
=3D=3D 3
> =A0 =A0 && =A0sscanf(other_buffer, "%d %d %d", &color, &price, &weight) =
=3D=3D 3
> =A0 =A0 && =A0needs_processing(color)) {
> =A0 =A0 =A0 =A0 compute_volume(length, width, height);
> =A0 =A0 =A0 =A0 compute_something_else(price, weight);
> =A0 =A0 }
>
> Along with 8 space aligned indentation, it's not that bad.

Or, because the condition should be made clear how about setting it
off as follows.

  if (
    sscanf(input_buffer, "%d %d %d", &length, &width, &height) =3D=3D 3 &&
    sscanf(other_buffer, "%d %d %d", &color, &price, &weight) =3D=3D 3 &&
    needs_processing(color)
    ) {
      compute_volume(length, width, height);
      compute_something_else(price, weight);
  }

I generally indent continuation lines half as much as the indent for a
block of code. In this case there are four spaces prior to the guarded
block of code and hence two spaces prior to each of the continuation
lines.

I can't recall seeing a recommendation for continuation lines
anywhere. I've just used this from my early programming days. It's
clear and consistent but I expect there are better schemes I've never
come across.

James
0
Reply james.harris.1 (384) 2/27/2010 9:53:42 AM

On 25 Feb, 17:03, Poster Matt <postermatt@no_spam_for_me.org> wrote:
> Eric Sosman wrote:
>
> > =A0 =A0 Contradict each other, of course! =A0Why did you ask?
>
> Given the amount of contradictory advise I'm getting in this
> thread I am beginning to wonder why myself. :)

I know you wrote this with a smiley and you are right there's been a
lot of differing advice but just as general observations:

1. the differences of opinion have been informative in their own right
and also served to highlight what preferences there are, and
2. some areas of consensus have come up.

All-in-all a useful discussion. Someone even managed to insert a word
none of us had ever heard of, bedizenry. (I think it was this thread.)
When I checked even Google only showed nine web hits and that's
including duplicates. Nice one, whoever that was. :-)


James
0
Reply james.harris.1 (384) 2/27/2010 10:26:03 AM

Stephen Sprunk <stephen@sprunk.org> writes:
> On 26 Feb 2010 09:12, Tim Streater wrote:
>> On 26/02/2010 14:51, Richard Heathfield wrote:
>>> Tim Streater wrote:
>>>> Trouble with tabs is, what is a tab?
>>>
>>> A quick way of inserting exactly two spaces into the source.
>> 
>> Since I don't know what tab setting you had when you handed me the code,
>> I think s/exactly two/a random number of/ applies here.
>
> That's a problem with _mixing tabs and spaces_, which is Evil(tm).
>
> If you use a tab character (inserted by pressing the tab key) for each
> level of indentation, each programmer can set the tab stops in his
> editor however he wants and it will look correct for everyone.

Only if everyone who ever modifies the code consistently uses tabs,
and only tabs, for indentation.

I really don't want to have to set the tabstops in my editor (and
in every other piece of software and/or hardware I might use to
look at the code, either on my own screen or on someone else's)
to the appropriate value for the particular file I'm looking at to
make it legible.

I might commonly examine a source file using any of vim, emacs, less,
cat (if it's very short), or one or more Windows-specific editors, or
I might print it, probably after using enscript to generate Postscript
output.  I'm also likely to use diff, among other things, to process
the source file as input.  I know how to set the tabstop width for
some of those, but certainly not all of them.

> (That introduces a new problem if you want to limit to 80 columns, but
> that can be remedied by saying "80 columns with X-character tabs".)

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 2/27/2010 10:26:16 AM

On 27/02/2010 08:32, Ben Finney wrote:
> Tim Streater<timstreater@waitrose.com>  writes:
>
>> Trouble with tabs is, what is a tab?
>
> <URL:http://www.jwz.org/doc/tabs-vs-spaces.html>
> <URL:http://c2.com/cgi/wiki?TabsVersusSpaces>
> <URL:http://www.codinghorror.com/blog/archives/001254.html>

Thanks, but I'm busy doing nothing this morning and so don't have time 
to read all that.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 2/27/2010 11:30:52 AM

Poster Matt <postermatt@no_spam_for_me.org> writes:
>Is CamelCase acceptable?

  If you write code for your own enjoyment, you can do it anyway
  that pleases you.

  If you write code in school or a company, the teacher or lead 
  programmer will answer this.

  If you ask me whether I like camel case in this case: No.

>2. My personal variable and function naming style is camel
>case, with variable names beginning with a lower case char
>and function names not. Is that acceptable, if not what is?
>Variables: int numFiles = 0;
>Functions: int CountNumFilesInDir(char* path);

  Are you aware that in C90, only the first 6 characters are
  required to be significant in external identifiers? Thus,

int fcount( char const * const directory )

  In C99,

int numberoffilesindir( char const * const path );

  or

int number_of_files_in_dir( char const * const path );

  . I do not use verbal phrase for the names of functions 
  whose main task is to return a value, so no �count�.

>EG. I like: char* firstName; and not so much: char *firstName;

  I agree, but the risk is that �char* a, b;� might look
  misleading to some beginners. So, I believe I might often
  use �char * a;�.

>EG. #define ErrorDirNotFound "The directory was not found."

  I am not aware of the advantages of using a macro here at all.

  Consistent handling of run-time errors is the most difficult
  part of programming. To prepare your program for
  internationalization, you might also use something like:

puts
( get_country_specific_message_text
  ( "The directory was not found." ))

>There are so many style guides out there, most of them say contradictory things 
>at one point or another. What do the pros do?

  They ask their boss / lead programmer to tell them what
  style to use. If they are a boss / lead programmer
  themselves, then they already should know.

>Finally, before someone points this out... I know if I'm coding for myself, and 
>not following somebody else's stylistic requirements, I can do whatever I want. 
>However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

  In this case, use code from authoritative sources as a
  template / role model:

    - programming examples in the Kernighan/Ritchie book
    - programming examples in the ISO standard for C
    - source code for the kernel and tools of your
      operating system

  I do not expect to see much camel case there.

0
Reply ram (2825) 2/27/2010 11:56:22 AM

On Fri, 26 Feb 2010 23:32:05 -0600
Kelsey Bjarnason <kbjarnason@gmail.com> wrote:

> 
> Because spaces, for purposes of indentation, are defective by design,
> and editors are generally built in such a manner as to use the right
> thing for the right job.  Spaces between words, etc, tabs for
> indentation.
> 

And someone prefer to use spaces instead of tabs. Then there's python
if one loves tabs so much to indent everything. Happy tabbing :)
0
Reply vlllnz (22) 2/27/2010 1:14:33 PM

scott@slp53.sl.home (Scott Lurndal) writes:
>   if (condition) {
>is preferred over
>   if (condition)
>   {
>Makes it much more likely that a properly written function will fit on a single
>page/screen.

  Not if you keep writing after the �{� as I do.

  Why?

  I want my code to express the structure.

  Which structure?

  The structure of the if statement, in this case.

  What is the structure of an if statement?

  According to ISO/IEC 9899:1999 (E)

selection-statement:
if ( expression ) statement

  So, there is a head

if ( expression ) 

  and a body

statement

  Thus,

if( expression )     /* head */
{ exam(); ple(); }   /* body */

  The separation between head and body in the deep structure
  beautifully alignes with the separation between the first
  and the second line in the visible surface structure. Thus,
  the surface structure exposes the deep structure in a
  not-misleading way. (Which to me is the generalized meaning
  of �structured programming�: expressing as much of the deep
  structure as possible already in the surface structure,
  which makes the code more readable.)

  I do not see how this takes more lines than

if( expression ) {
  exam(); ple(); }

  or even

if( expression ) {
  exam(); ple(); 
  }

  Moreover, why would anyone sane in his mind compose a line
  of the head of a structure /and the first character of its
  body/ with the rest of the body following in another line?

  As a comparision, in writing, we have headings and text body:

      The Creation

      In the beginning God created the heaven and the earth.

  Now, why would I write the heading /and the first word of
  its body/ on a line, as in the following example?

      The Creation In

      the beginning God created the heaven and the earth.

  If you put that �In� on the same line as your heading you'll
  just look like a fool in front of your friends and colleagues. 

0
Reply ram (2825) 2/27/2010 1:52:10 PM

ike@localhost.claranet.nl (Ike Naar) writes:

>Then, it's not always black and white.
>Consider the case where a condition does not fit on a single line:

>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>        needs_processing(color)) {
>        compute_volume(length, width, height);
>        compute_something_else(price, weight);
>    }

>vs.

>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>        needs_processing(color))
>    {
>        compute_volume(length, width, height);
>        compute_something_else(price, weight);
>    }

>In the first case, it is hard to see where the condition ends
>and where the body starts. In the second case it's obvious.
>Don't you think that the opening brace on its own line here improves
>the readability?

I call a strawman; a proper c-style will not allow the first form;
e.g., at Sun our style requires this form:

	if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
	    sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
	    needs_processing(color)) {
		compute_volume(length, width, height);
		compute_something_else(price, weight);
	}


It's clear what the condition is and where the body starts.

Things I absolutely hate in some c-styles are:


	if(condition)


"if" is a not a *function* it shouldn't look like one.

cstyles which require additional parantheses

	if ((sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3) &&
	    (sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3) &&


Some C code looks like as if it is written with a leaking fountain pen
on smudged and crumpled paper.

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 2/27/2010 1:56:54 PM

Kelsey Bjarnason <kbjarnason@gmail.com> writes:

>On Fri, 26 Feb 2010 11:28:19 -0800, Keith Thompson wrote:

>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>> Tim Streater wrote:
>>> <snip>
>>>
>>>> Trouble with tabs is, what is a tab?
>>>
>>> A quick way of inserting exactly two spaces into the source.
>> 
>> The One True Tabstop Width is 8.

>Three, actually.  Okay, 8, if you're stuck using output devices from the 
>1960's which didn't allow user-defined tab spaces, but for how many 
>people is this true anymore?

You don't quite understand why a ne True Tabstop Width is 8?

It is because *other* *people* want to look at your code.

If you file contains real tabstops they better make sure that the file
looks right when displayed with a standard terminal.

>Now imagine if they were using spaces.  This guy uses two, the next guy 
>uses three, the third guy uses 4, the fourth guy uses 5, some other guy 
>uses 8.

>With tabs, at least just by setting your tab stops, you can get a degree 
>of consistency.  Have fun sorting out the nightmare of inconsistency 
>spaces lead to.

No, because you make the file non-portable, unless you save with
spaces and not with tabstops.

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 2/27/2010 2:00:44 PM

ike@localhost.claranet.nl (Ike Naar) writes:
>Consider the case where a condition does not fit on a single line:
>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>        needs_processing(color)) {
>        compute_volume(length, width, height);
>        compute_something_else(price, weight);
>    }

  I use the same rules for parentheses as for square brackets
  and curly braces and thus, format this as follows.

if
( sscanf( input_buffer, "%d %d %d", &length, &width, &height )== 3 &&
  sscanf( other_buffer, "%d %d %d", &color,  &price, &weight )== 3 &&
  needs_processing( color )) 
{ compute_volume( length, width, height );
  compute_something_else( price, weight ); }

  One Way to Format Parentheses

  There are several different ways to format texts with braces
  and parentheses. One of them is being described here.

  Indentation within Braces

  An indentation of just one space often is too small to be seen
  clearly, because the natural width and form of characters
  often varies by an amount that is not very much smaller than a
  space. Therefore, the indentation should amount to at least
  two positions. In order not to waste horizontal spaces, an
  indentation of exactly two positions is chosen. This means,
  that the left position of the next level is two larger than
  the position of the directly enclosing level.

  Indentation by two positions within a block

{ ++x;
  ++x; }
^ ^
0 2

  Bad: A small indentation by one position is not always visible
  clearly

{++x;
 ++x; }

  Good: The indentation by two positions is visible clearly

{ ++x;
  ++x; }

  Bad: A large indentation by more than two positions wastes
  horizontal space with no additional benefit

{    ++x;
     ++x; }

Spaces within braces

  In mathematics, there are often no spaces at the inner side of
  parentheses or braces in expressions, but spaces are used
  indeed at the inner side of braces in set notation, when the
  braces contain a description (not when they contain a list).

  Spaces in set notation

{ x | x  > 2 }

  This style is adopted here: One space is written at the inner
  side of braces.

  Spaces at the inner side of parentheses within a block

{ ++x; }

  This style is consistent with the indentation by two
  positions, because only using this style, corresponding parts
  of two lines have the same position.

  Bad: No space after the first brace, the two statements are
  misaligned

{++x;
  ++x; }

  Good: One space after the first brace, the two statements are
  properly aligned

{ ++x;
  ++x; }

  Bad: Two spaces after the first brace, the two statements are
  misaligned

{  ++x;
  ++x; }

  There are some exceptions to this rule: No spaces are used
  within empty braces "{}" and between two or more closing
  braces of the same direction "}}", except, when the first one
  of them is part of an empty pair "{} }" (an empty pair of
  braces if treated like a single non-braces character).

  Unified rules for all Brackets

  For simplicity and uniformity, the rules from above apply to
  all kinds of brackets, including parentheses, braces (curly
  brackets), square brackets, and angle brackets.

  Spaces within parentheses and square brackets

{ y = f( x )+ g() + a[ 2 ]; }

  Binary operators are sorrounded by a space, but the space is
  omitted, when there already is a space on the other side of a
  sequence of brackets directly beside the operator: By this rule,
  " )+" is written instead of " ) +".

  Representation of the Syntactical Structure

  A method declaration in Java consists of a head and a body.
  The following representation shows this structure:

  Good formatting according to the structure

void alpha() // head
{ beta(); }  // body

  The following formatting is misleading, because the line break
  does not match the structural break:

  Bad line break within the body

void alpha() { // head and the beginning of the body
  beta(); }    // the rest of the body

  This formatting also would make no sense for blocks within
  blocks. So it is often not used for such blocks. Therefore
  even the adopters of this style can not use it uniformly.

  Opening Braces Look Like "bullets"

  There is a well known style to publish lists in typography
  using bullets sticking out on the left, looking like this:

  Common list representation with bullets in typography

o This is the first point
  of this list, it is written
  here just as an example.

o Here is another entry

o This is another example given
  just as an example to show
  an example

  The braces of the beginnings of blocks stand out on the left
  just the same, when the formatting being described here is
  used, so they look quite naturally as beginning-of-a-block
  markers, when one is used to the typographical list notation:

  Left braces look like bullets to mark blocks

{ printf(); printf();
  printf(); printf(); printf();
  printf(); printf(); }

{ printf(); printf(); }

{ printf(); printf(); printf();
  printf(); printf();
  printf(); }

  Neutrality

  Someone wrote this C code:

while( fgets( eingabe, sizeof eingabe, stdin ))
  if( sscanf( eingabe, "%d", &wert )!= 1 )
    fprintf( stderr, "Please enter a number!\n" );
  else
    summe += wert;

  It amazes me that I can add braces by my style conventions
  (not changing the meaning of the code)
  without the need to change the position of any character of
  the given code or need to change the overall number of lines:

  The code from above plus braces

while( fgets( eingabe, sizeof eingabe, stdin ))
{ if( sscanf( eingabe, "%d", &wert )!= 1 )
  { fprintf( stderr, "Please enter a number!\n" ); }
  else
  { summe += wert; }}

  Insofar, my bracing style might be considered non-obtrusive.

  Lines per Contents

  Lines containing only a single brace waste vertical space, so
  less contents fits on the same screen space. Therefore, I usually
  avoid them, but sometimes I do use them, when this helps to
  increase readability. I also might temporarily use them when editing
  a section of code. Of course, they would help programmers paid or
  being judged by the lines-of-code productivity.


0
Reply ram (2825) 2/27/2010 2:05:55 PM

ram@zedat.fu-berlin.de (Stefan Ram) writes:
>if
>( sscanf( input_buffer, "%d %d %d", &length, &width, &height )== 3 &&
>  sscanf( other_buffer, "%d %d %d", &color,  &price, &weight )== 3 &&
>  needs_processing( color )) 
>{ compute_volume( length, width, height );
>  compute_something_else( price, weight ); }

 ^
 '---- What I like about this is:

       This is an if statement with two variable constituents:
       an expression and a statement.

       This is the macrostructure.

       The major questions one encounters when reading are:

           - What a kind of entity is this at all?

       And then, having learned that it is an if statement:

           - Where is its expression?

           - Where is its statement?

       And it are exactly the answers to these three questions
       that are each marked with a character in the leftmost column.

       So the type of the entity and its two constituents
       clearly stand out graphically (visually). Albeit in a 
       manner not too obtrusive and not wasting lines.

       Now we can compare this with:

>>     if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>>         sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>>         needs_processing(color)) {
>>         compute_volume(length, width, height);
>>         compute_something_else(price, weight);
>>     }

       Here the start and end of the statement are marked in the 
       leftmost column. This is also not bad, but the important
       separation between the expression and the statement of the
       if is �hidden� in the �center� of this character structure.

0
Reply ram (2825) 2/27/2010 3:51:58 PM

On 27 Feb, 13:56, Casper H.S. Dik <Casper....@Sun.COM> wrote:
> i...@localhost.claranet.nl (Ike Naar) writes:

> Things I absolutely hate in some c-styles are:
>
> =A0 =A0 =A0 =A0 if(condition)
>
> "if" is a not a *function* it shouldn't look like one.

I write it like this

   if (condition)
       some_func (x);

and 'if' still doesn't look like a function to me



0
Reply nick_keighley_nospam (4574) 2/27/2010 4:24:38 PM

On 27 Feb, 08:39, James Harris <james.harri...@googlemail.com> wrote:

> Windows Notepad users are stuck with 8. Windows Wordpad users seem to
> be stuck with 6. These are not earlier than the 1980s.
>
> Come to think of it, apart from those two programs what do Windows
> users use to enter and edit source code?

the IDE, ConText, emacs, Word

0
Reply nick_keighley_nospam (4574) 2/27/2010 4:30:16 PM

On 27 Feb, 05:32, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:

> > Trouble with tabs is, what is a tab?
>
> It's a character, often ASCII 9, which tells your editor to indent (or,
> on removal, unindent) by whatever number of columns is required to bring
> things in line with the next (previous) tab stop.

so your layout is tab-stop dependent


> Contrast that to hitting delete on a line which uses spaces instead of
> tabs. =A0All this does is mess up the formatting, as the editor is almost
> certain to treat a space as a _space_, as it should, not as a tab, which
> it _shouldn't_, because the character involved is not a tab, but a space.

get a better editor


> Then, of course, there's inserting. =A0Hit space. =A0See how many columns=
 the
> line indents. =A0One, isn't it?

but if I hit 'tab' my editor inserts four spaces. Or rather enough
spaces to make it a multiple of four or to line up with the preceeding
line

> =A0Why is that? =A0Oh, yes, because spaces
> aren't tabs, and editors won't treat them as tabs. =A0Tabs are tabs, and
> editors treat them that way.

mine doesn't

> AFAIK, even Emacs and vi can cope with tabs. =A0I've yet to meet _any_
> editor which, when you delete a space, correctly determines that you
> really meant to delete four spaces, and removes that many,

ConTEXT (on Windows)

> or, when you
> hit the spacebar, correctly figures out that you actually meant a tab,
> not a space, and thus inserts 4 (or is it 3? =A08? =A05?) spaces.

but TAB does that for me

> > I use the tab key but my editor
> > (TextWrangler) just converts them to spaces. Why should spaces bother a=
n
> > editor, anyway?

well I'd argue you aren't using TABs in your source text

> Because spaces, for purposes of indentation, are defective by design, and
> editors are generally built in such a manner as to use the right thing
> for the right job. =A0Spaces between words, etc, tabs for indentation.

0
Reply nick_keighley_nospam (4574) 2/27/2010 4:38:08 PM

On 27 Feb, 06:00, Richard <rgrd...@gmail.com> wrote:
> Kelsey Bjarnason <kbjarna...@gmail.com> writes:
> > [snips]
>
> > On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:
>
> >> Trouble with tabs is, what is a tab?
>
> > It's a character, often ASCII 9, which tells your editor to indent (or,
> > on removal, unindent) by whatever number of columns is required to brin=
g
> > things in line with the next (previous) tab stop.
>
> Something tells me Tim might have know that.
>
>
>
> > Contrast that to hitting delete on a line which uses spaces instead of
> > tabs. =A0All this does is mess up the formatting, as the editor is almo=
st
> > certain to treat a space as a _space_, as it should, not as a tab, whic=
h
> > it _shouldn't_, because the character involved is not a tab, but a
> > space.
>
> Not with any half competent editor.
>
>
>
> > Then, of course, there's inserting. =A0Hit space. =A0See how many colum=
ns the
> > line indents. =A0One, isn't it? =A0Why is that? =A0Oh, yes, because spa=
ces
> > aren't tabs, and editors won't treat them as tabs. =A0Tabs are tabs, an=
d
> > editors treat them that way.
>
> And often treat spaces as tabs too. press left or right or delete on y
> white space area and it deletes to a tap stop.
>
>
>
> > AFAIK, even Emacs and vi can cope with tabs. =A0I've yet to meet _any_
>
> Even? Emacs is probably the most advanced editor out there. And vi one
> of the most popular programmers editor.
>
> > editor which, when you delete a space, correctly determines that you
> > really meant to delete four spaces, and removes that many, or, when you
> > hit the spacebar, correctly figures out that you actually meant a tab,
> > not a space, and thus inserts 4 (or is it 3? =A08? =A05?) spaces.
>
> >> I use the tab key but my editor
> >> (TextWrangler) just converts them to spaces. Why should spaces bother =
an
> >> editor, anyway?
>
> They don't if you're half competent and configure it properly.
>
>
>
> > Because spaces, for purposes of indentation, are defective by design,
> > and
>
> What total bullshit. Most people use spaces for indentation.
>
> > editors are generally built in such a manner as to use the right thing
> > for the right job. =A0Spaces between words, etc, tabs for indentation.
>
> Totally and utterly wrong. Its rare to find tabs used anymore. Most
> editors are LSEs (language sensitive editors) and indent automatically
> based on a configured language layout.

For once, I agree with one of your posts!


0
Reply nick_keighley_nospam (4574) 2/27/2010 4:39:06 PM

>
>
> If you file contains real tabstops they better make sure that the file 
> looks right when displayed with a standard terminal.
>
"Standard terminal"s, eh?  Where in IEEE 1003.1:2004 does it specify how 
many spaces a terminal in TAB3 mode actually expands to?  Where does it 
specify what the default tabstops are when one hasn't run the tabs command?

0
Reply J.deBoynePollard-newsgroups (95) 2/27/2010 5:22:03 PM

Nick Keighley <nick_keighley_nospam@hotmail.com> writes:

>On 27 Feb, 13:56, Casper H.S. Dik <Casper....@Sun.COM> wrote:
>> i...@localhost.claranet.nl (Ike Naar) writes:

>> Things I absolutely hate in some c-styles are:
>>
>> =A0 =A0 =A0 =A0 if(condition)
>>
>> "if" is a not a *function* it shouldn't look like one.

>I write it like this

>   if (condition)
>       some_func (x);

>and 'if' still doesn't look like a function to me


It is fine with the space but not without (if() vs if ())

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 2/27/2010 5:50:39 PM

ram@zedat.fu-berlin.de (Stefan Ram) writes:
> ike@localhost.claranet.nl (Ike Naar) writes:
>>Consider the case where a condition does not fit on a single line:
>>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>>        needs_processing(color)) {
>>        compute_volume(length, width, height);
>>        compute_something_else(price, weight);
>>    }
>
>   I use the same rules for parentheses as for square brackets
>   and curly braces and thus, format this as follows.
>
> if
> ( sscanf( input_buffer, "%d %d %d", &length, &width, &height )== 3 &&
>   sscanf( other_buffer, "%d %d %d", &color,  &price, &weight )== 3 &&
>   needs_processing( color )) 
> { compute_volume( length, width, height );
>   compute_something_else( price, weight ); }

This must have been invented by someone who never changes the first
and last lines of a block and who never appends lines to blocks :->.
0
Reply rweikusat (2679) 2/27/2010 8:17:17 PM

Casper H.S. Dik wrote:
> 
> Things I absolutely hate in some c-styles are:
> 
> 
> 	if(condition)
> 
> 
> "if" is a not a *function* it shouldn't look like one.

Almost as bad a styles that require parentheses on return; "return" is 
not a *function* it shouldn't look like one!

-- 
Ian Collins
0
Reply ian-news (9878) 2/27/2010 8:28:46 PM

Ian Collins <ian-news@hotmail.com> writes:

> Casper H.S. Dik wrote:
>>
>> Things I absolutely hate in some c-styles are:
>>
>>
>> 	if(condition)
>>
>>
>> "if" is a not a *function* it shouldn't look like one.
>
> Almost as bad a styles that require parentheses on return; "return" is
> not a *function* it shouldn't look like one!

There's something fundamentally wrong with the contrast between these
two programs as a result of that:

#include <stdlib.h>

int main(void) {
    return EXIT_FAILURE;
}

-----
#include <stdlib.h>

int main(void) {
    exit(EXIT_FAILURE);
}
--------
-- 
Online waterways route planner            | http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
0
Reply 3-nospam (285) 2/27/2010 8:40:27 PM

[snips]

On Sat, 27 Feb 2010 14:00:44 +0000, Casper H.S. Dik wrote:

>>> The One True Tabstop Width is 8.
> 
>>Three, actually.  Okay, 8, if you're stuck using output devices from the
>>1960's which didn't allow user-defined tab spaces, but for how many
>>people is this true anymore?
> 
> You don't quite understand why a ne True Tabstop Width is 8?

Because, in the 1960's and earlier, devices weren't capable of coping 
with user-defined tab stops.  Welcome to the new world.

> It is because *other* *people* want to look at your code.

Which they can readily do, simply by setting their tab stops to whatever 
their personal preferences are.

> If you file contains real tabstops they better make sure that the file
> looks right when displayed with a standard terminal.

Set tabstop to 2, 3, 4, 5, 8, 179, whatever looks best to your 
preferences.  Unlike with spaces, where you have no control whatsoever.  
Not sure what your point is here... that because tabs allow the user to 
control the display layout, it's better to use spaces which don't?

>>Now imagine if they were using spaces.  This guy uses two, the next guy
>>uses three, the third guy uses 4, the fourth guy uses 5, some other guy
>>uses 8.
> 
>>With tabs, at least just by setting your tab stops, you can get a degree
>>of consistency.  Have fun sorting out the nightmare of inconsistency
>>spaces lead to.
> 
> No, because you make the file non-portable, unless you save with spaces
> and not with tabstops.

Well, yes, okay, if one is in fact using a device so ancient it can't 
handle user-defined tab stops, then we can agree, using tabs is not 
"portable" to that device.

I've been in computing for about 30 years now, and offhand, I can recall 
precisely _one_ such device I've ever used - a line printer which hasn't 
been actually used since about 1975.

0
Reply kbjarnason (4583) 2/27/2010 9:12:50 PM

>
>
> Set tabstop to 2, 3, 4, 5, 8, 179, whatever looks best to your 
> preferences.
>
tabs 1,+1,+2,+3,+5,+8,+13,+21,+34,+55,+89

0
Reply J.deBoynePollard-newsgroups (95) 2/27/2010 10:30:00 PM

Richard Heathfield wrote:
> Ian Collins wrote:
>> Richard wrote:
> <snip>
> 
>>> It is ludocrous to recommend the second form. ALL it does is waste a
>>> line. Indentation is there for a reason. We dont need to see the opening
>>> bracket on its own wasted line.
>>
>> What's the going rate for a line these days?
> 
> People should avoid trying to answer that question until they have
> checked their answer in the debugger.
> 

Cost of a line feed is the same as the cost of a space character.


0
Reply gldncagrls (469) 2/27/2010 10:55:23 PM

James Harris wrote:
<snip>
> 
> Come to think of it, [...] what do Windows
> users use to enter and edit source code?

gvim

> I don't think I ever use tabs when typing a high level language. I
> always use spaces - just two per indent.

Ah, at last, a true Scotsman. :-)

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 2/27/2010 10:59:53 PM

[snips]

On Sat, 27 Feb 2010 00:39:29 -0800, James Harris wrote:

>> Three, actually.  Okay, 8, if you're stuck using output devices from
>> the 1960's which didn't allow user-defined tab spaces, but for how many
>> people is this true anymore?
> 
> Windows Notepad users are stuck with 8. Windows Wordpad users seem to be
> stuck with 6. These are not earlier than the 1980s.

People actually *use* Notepad?  For *code*?  TextPad, NotePad++, about 
1,873,000 other options, and you use *notepad*?

Okay, fine, this is a case of blame the tool.  The one between the 
keyboard and the chair. :)

> Come to think of it, apart from those two programs what do Windows users
> use to enter and edit source code?

Endless IDEs.  Endless text editors not so crippled.  Ones with little 
things such as auto-indent, or syntax highlighting, or code folding, and 
a host of other features. 

> I don't think I ever use tabs when typing a high level language. I
> always use spaces - just two per indent. Then there are no portability
> problems

Unless one is working on your code and someone else's which uses three 
spaces.  Or four.  Or eight.  In which case it's not merely a mess, but 
an unrecoverable mess.

> IMHO embedded tabs in source code should be consigned to the wastebin of
> history as just one of those non-printable characters we used to hate.
> Why? Well, they generate a different result depending on where they are
> placed and *look like* something else - i.e. one or more spaces. They
> are, to an extent, hidden.

Which they're meant to be.  They're a layout item, not a visible item.  
Like spaces.  Or newlines.

0
Reply kbjarnason (4583) 2/27/2010 11:06:12 PM

[snips]

On Sat, 27 Feb 2010 07:00:50 +0100, Richard wrote:

>> Contrast that to hitting delete on a line which uses spaces instead of
>> tabs.  All this does is mess up the formatting, as the editor is almost
>> certain to treat a space as a _space_, as it should, not as a tab,
>> which it _shouldn't_, because the character involved is not a tab, but
>> a space.
> 
> Not with any half competent editor.

Really.  Explain to the class the AI process involved in determining 
whether a space is actually a space, or one of several spaces 
masquerading as a tab, and how the editor - in the absence of tab stops - 
tells the difference between one space, two spaces, one tab's worth of 
spaces, two tab's worth of spaces...

Granted, some will - if you use the tab key to indent/unindent, simply 
add or remove to the next tab stop's worth, but all you're doing there is 
using tabs and tab stops and converting to spaces for some as yet 
unexplained reason.

>> Then, of course, there's inserting.  Hit space.  See how many columns
>> the line indents.  One, isn't it?  Why is that?  Oh, yes, because
>> spaces aren't tabs, and editors won't treat them as tabs.  Tabs are
>> tabs, and editors treat them that way.
> 
> And often treat spaces as tabs too. press left or right or delete on y
> white space area and it deletes to a tap stop.

If I press "delete" in an editor once, and it deletes more than one 
character, the editor is by definition broken and needs to be fixed or 
chucked.  The only time an editor should _ever_ do more than one thing 
per keystroke is in the case of a macro or function key.

>> AFAIK, even Emacs and vi can cope with tabs.  I've yet to meet _any_
> 
> Even? Emacs is probably the most advanced editor out there. And vi one
> of the most popular programmers editor.

Which suggests they should be able to cope with tabs.

>> Because spaces, for purposes of indentation, are defective by design,
>> and
> 
> What total bullshit. Most people use spaces for indentation.

Yes, and thus we end up with one piece of code using two spaces, another 
using three, another using 4, or 5, or 8, and any attempt to make this 
make sense is doomed to failure - because the whole process is defective 
by design.

>> editors are generally built in such a manner as to use the right thing
>> for the right job.  Spaces between words, etc, tabs for indentation.
>>
>>
> Totally and utterly wrong.

Really?  You use editors that can't handle tabs and tabstops?  Why would 
you rely on such crippled tools?


> Its rare to find tabs used anymore. Most
> editors are LSEs (language sensitive editors) and indent automatically
> based on a configured language layout.

Which works if - and only if - they're not being overriden by some 
goober's insistence upon doing the wrong thing by using non-indentation 
characters for purposes of indentation.

Especially true when working with multiple developers and sometihng like 
CVS, where such auto-mangling, without a de-mangling phase on checkin, 
simply leads to a chaotic mess.

Really, why would anyone want to insist on using the wrong tool for the 
job?  Spaces for indendation, Pascal compilers for C code, makes no sense.

0
Reply kbjarnason (4583) 2/27/2010 11:15:45 PM

On Sat, 27 Feb 2010 08:38:08 -0800, Nick Keighley wrote:

> On 27 Feb, 05:32, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
>> On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:
> 
>> > Trouble with tabs is, what is a tab?
>>
>> It's a character, often ASCII 9, which tells your editor to indent (or,
>> on removal, unindent) by whatever number of columns is required to
>> bring things in line with the next (previous) tab stop.
> 
> so your layout is tab-stop dependent

And variable, to the individual coder's tastes, simply by their choice of 
tab stops, without messing it up for everyone else.  Yes, indeed, tab-
stop dependent, not "whatever number of spaces I think should be inserted 
here" dependent.

>> Contrast that to hitting delete on a line which uses spaces instead of
>> tabs.  All this does is mess up the formatting, as the editor is almost
>> certain to treat a space as a _space_, as it should, not as a tab,
>> which it _shouldn't_, because the character involved is not a tab, but
>> a space.
> 
> get a better editor

I have a better editor.  One that understands the difference between 
spaces and tabs.  One that does *not* do something as brain-dead as 
deleting _multiple_ characters when I press delete once.  Any editor 
which deletes multiple items on a single delete simply cannot be trusted, 
it's liable to destroy something.

>> Then, of course, there's inserting.  Hit space.  See how many columns
>> the line indents.  One, isn't it?
> 
> but if I hit 'tab'

No, sorry, we're using spaces here, not tabs.  If you want to insert 
tabs, then by all means, use tabs.  But then you're on my side of the 
fence, with spaces being defective by design for indent.  If they weren't 
defective by design, you wouldn't be using tab instead of space.


>>  Why is that?  Oh, yes, because spaces
>> aren't tabs, and editors won't treat them as tabs.  Tabs are tabs, and
>> editors treat them that way.
> 
> mine doesn't

Then you  should get an editor that works.

>> or, when you
>> hit the spacebar, correctly figures out that you actually meant a tab,
>> not a space, and thus inserts 4 (or is it 3?  8?  5?) spaces.
> 
> but TAB does that for me

Exactly.  Tab.  Not space.  

If your editor - and the notion of spaces for indentation - weren't 
defective by design, you wouldn't need to use a special key to insert 
spaces; that's why you have a space bar.  The fact you have to resort to 
something entirely different, the tab key, is prima facie evidence the 
whole notion of spaces to indent is as defective as it appears.

Now, if your editor worked properly, using tabs instead of spaces, with 
the tab key inserting tabs as it should, then when viewed on someone 
else's display, rather than yours, it would show the code as *they* 
prefer to view it, rather than as *you* have decided is the only true way 
which everyone should be forced to view it in.

Really, isn't this just a case of imposing your own layout conventions on 
others, rather than using a common sense approach which actually lets 
everyone view the code in their own preferred manner?  Without having to 
defeat the needless additional complication of converting some godawful 
arrangement you happen to like into something actually manageable?

0
Reply kbjarnason (4583) 2/27/2010 11:23:52 PM

Jonathan de Boyne Pollard <J.deBoynePollard-newsgroups@NTLWorld.COM>
writes:

> > Set tabstop to 2, 3, 4, 5, 8, 179, whatever looks best to your
> > preferences.
> >
> tabs 1,+1,+2,+3,+5,+8,+13,+21,+34,+55,+89

You're just telling fibs again.

<snare roll>

-- 
 \              “Programs must be written for people to read, and only |
  `\        incidentally for machines to execute.” —Abelson & Sussman, |
_o__)              _Structure and Interpretation of Computer Programs_ |
Ben Finney
0
Reply unix49 (48) 2/28/2010 12:08:59 AM

In article <4b8924a6$0$22939$e4fe514c@news.xs4all.nl>,
Casper H.S. Dik  <Casper.Dik@Sun.COM> wrote:
>ike@localhost.claranet.nl (Ike Naar) writes:
>>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>>        needs_processing(color)) {
>>        compute_volume(length, width, height);
>>        compute_something_else(price, weight);
>>    }
>
>>vs.
>
>>    if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>>        sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>>        needs_processing(color))
>>    {
>>        compute_volume(length, width, height);
>>        compute_something_else(price, weight);
>>    }
>
>>In the first case, it is hard to see where the condition ends
>>and where the body starts. In the second case it's obvious.
>>Don't you think that the opening brace on its own line here improves
>>the readability?
>
>I call a strawman; a proper c-style will not allow the first form;
>e.g., at Sun our style requires this form:
>
>	if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) == 3 &&
>	    sscanf(other_buffer, "%d %d %d", &color, &price, &weight) == 3 &&
>	    needs_processing(color)) {
>		compute_volume(length, width, height);
>		compute_something_else(price, weight);
>	}

I don't think your strawman call is justified.
My "first case" is the output of (gnu) "indent -kr".
0
Reply ike5 (222) 2/28/2010 12:20:18 AM

>
>
> Cost of a line feed is the same as the cost of a space character
>
That is only the case when one's terminal is set to NL0 mode and isn't 
set to ONLCR or ONLRET modes, or it is set to both CR0 and NL0 modes.

0
Reply J.deBoynePollard-newsgroups (95) 2/28/2010 2:43:26 AM

we may be talking at cross purposes as well as disagreeing. We also
may be starting to repeat ourselves. Editors and code layouts are very
personnel things.


On 27 Feb, 23:23, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> On Sat, 27 Feb 2010 08:38:08 -0800, NickKeighleywrote:
> > On 27 Feb, 05:32, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
> >> On Fri, 26 Feb 2010 12:29:13 +0000, Tim Streater wrote:


> >> > Trouble with tabs is, what is a tab?
>
> >> It's a character, often ASCII 9, which tells your editor to indent (or=
,
> >> on removal, unindent) by whatever number of columns is required to
> >> bring things in line with the next (previous) tab stop.

ok. A <tab> character is ASCII 9 if found in source text (I know the
world isn't ASCII, but a bit of concreteness here makes life a little
easier). A <tab> is also a key on many keyboards. I'll try and
distinguish <tab-char> from <tab-key>.

> > so your layout is tab-stop dependent

that is there are <tab-chars> in your source text.

> And variable, to the individual coder's tastes, simply by their choice of
> tab stops, without messing it up for everyone else. =A0Yes, indeed, tab-
> stop dependent, not "whatever number of spaces I think should be inserted
> here" dependent.

one difficulty with embedded <tab-chars> as the only layout character
is that you lose fine control.

void pippo (int n)
{
    if ((n =3D=3D PHOTON) ||
        (n =3D=3D LEPTON) ||
        (n =3D=3D HADRON))
    {
        send_msg ("claim nobel!");
    }
}

I don't see how this layout can survive spaceless layout or variable
tab stops. Presumably you don't require layout like this.

> >> Contrast that to hitting delete on a line which uses spaces instead of
> >> tabs. =A0All this does is mess up the formatting, as the editor is alm=
ost
> >> certain to treat a space as a _space_, as it should, not as a tab,
> >> which it _shouldn't_, because the character involved is not a tab, but
> >> a space.
>
> > get a better editor
>
> I have a better editor. =A0

:-)


> One that understands the difference between
> spaces and tabs. =A0One that does *not* do something as brain-dead as
> deleting _multiple_ characters when I press delete once. =A0Any editor
> which deletes multiple items on a single delete simply cannot be trusted,
> it's liable to destroy something.

no. My editor (this is actually a configurable option) only does this
for spaces. I assure you it works well in practice.

> >> Then, of course, there's inserting. =A0Hit space. =A0See how many colu=
mns
> >> the line indents. =A0One, isn't it?
>
> > but if I hit 'tab'

If I hit the <tab-key> it inserts N spaces. I still use the <tab-key>
to indicate layout but the editor puts <spaces> in the source text.

> No, sorry, we're using spaces here, not tabs. =A0If you want to insert
> tabs, then by all means, use tabs.

If I want to insert <tab-chars> (eg. for the dreaded make file) I have
to change an option on my editor. Normally I do not want to insert
<tab-chars>

>=A0But then you're on my side of the
> fence, with spaces being defective by design for indent.

this is phrasing it rather strongly. There are plenty of people who
have a different opinion from you.

>=A0If they weren't
> defective by design, you wouldn't be using tab instead of space.

is that <tab-char> or <tab-key>?

<snip>

[it's getting repetitive]

> If your editor - and the notion of spaces for indentation - weren't
> defective by design, you wouldn't need to use a special key to insert
> spaces; that's why you have a space bar. =A0The fact you have to resort t=
o
> something entirely different, the tab key, is prima facie evidence the
> whole notion of spaces to indent is as defective as it appears.

this is opinion masquerading as fact. I use the <tab-key> to indicate
my layout requirement; the editor "compiles" this into <space>
characters. A one-to-one mapping of key to text is not a requirement
(plainly not or delete and backspace would always work the way I
wanted them to on Unix!).

> Now, if your editor worked properly, using tabs instead of spaces, with
> the tab key inserting tabs as it should, then when viewed on someone
> else's display, rather than yours, it would show the code as *they*
> prefer to view it, rather than as *you* have decided is the only true way
> which everyone should be forced to view it in.

I like finer control over my layout than you do apparently

> Really, isn't this just a case of imposing your own layout conventions on
> others, rather than using a common sense approach which actually lets
> everyone view the code in their own preferred manner? =A0Without having t=
o
> defeat the needless additional complication of converting some godawful
> arrangement you happen to like into something actually manageable?

but you also require others to agree to your conventions.

I bet you'd hate this approach

Code laid out like this with 4 character indent
xxxx
    yyyy
        zzzz
            wwww

and using S and T to represent the "layout charcaters" actually looked
like this

xxxx
SSSSyyyy
Tzzzz
TSSSSwwww


the worst or all possible worlds!









0
Reply nick_keighley_nospam (4574) 3/1/2010 9:06:04 AM

Ian Collins <ian-news@hotmail.com> writes:
>Richard wrote:

>> It is ludocrous to recommend the second form. ALL it does is waste a
>> line. Indentation is there for a reason. We dont need to see the opening
>> bracket on its own wasted line.
>
>What's the going rate for a line these days?

From the utility 'sloccount' for one of our projects:

Totals grouped by language (dominant language first):
cpp:          98544 (88.41%)
ansic:        10896 (9.78%)
asm:           1906 (1.71%)
sh:              59 (0.05%)
python:          56 (0.05%)




Total Physical Source Lines of Code (SLOC)                = 111,461
Development Effort Estimate, Person-Years (Person-Months) = 28.22 (338.60)
 (Basic COCOMO model, Person-Months = 2.4 * (KSLOC**1.05))
Schedule Estimate, Years (Months)                         = 1.91 (22.87)
 (Basic COCOMO model, Months = 2.5 * (person-months**0.38))
Estimated Average Number of Developers (Effort/Schedule)  = 14.81
Total Estimated Cost to Develop                           = $ 3,811,717
 (average salary = $56,286/year, overhead = 2.40).
SLOCCount, Copyright (C) 2001-2004 David A. Wheeler
SLOCCount is Open Source Software/Free Software, licensed under the GNU GPL.
SLOCCount comes with ABSOLUTELY NO WARRANTY, and you are welcome to
redistribute it under certain conditions as specified by the GNU GPL license;
see the documentation for details.
Please credit this data as "generated using David A. Wheeler's 'SLOCCount'."
0
Reply scott 3/1/2010 6:07:00 PM

James Harris <james.harris.1@googlemail.com> writes:
>On 27 Feb, 05:19, William Ahern <will...@wilbur.25thandClement.com>
>wrote:
>> In comp.lang.c Ike Naar <i...@localhost.claranet.nl> wrote:
>> <snip>
>>
>> > Consider the case where a condition does not fit on a single line:
>>
>> > =A0 =A0 if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) =
>=3D=3D 3 &&
>> > =A0 =A0 =A0 =A0 sscanf(other_buffer, "%d %d %d", &color, &price, &weigh=
>t) =3D=3D 3 &&
>> > =A0 =A0 =A0 =A0 needs_processing(color)) {
>> > =A0 =A0 =A0 =A0 compute_volume(length, width, height);
>> > =A0 =A0 =A0 =A0 compute_something_else(price, weight);
>> > =A0 =A0 }
>>
>> I agree that that's a sore spot. But in complex conditions I often like t=
>o
>> align the logical operators w/ the if statement.
>>
>> =A0 =A0 if (sscanf(input_buffer, "%d %d %d", &length, &width, &height) =
>=3D=3D 3
>> =A0 =A0 && =A0sscanf(other_buffer, "%d %d %d", &color, &price, &weight) =
>=3D=3D 3
>> =A0 =A0 && =A0needs_processing(color)) {
>> =A0 =A0 =A0 =A0 compute_volume(length, width, height);
>> =A0 =A0 =A0 =A0 compute_something_else(price, weight);
>> =A0 =A0 }
>>
>> Along with 8 space aligned indentation, it's not that bad.
>
>Or, because the condition should be made clear how about setting it
>off as follows.
>
>  if (
>    sscanf(input_buffer, "%d %d %d", &length, &width, &height) =3D=3D 3 &&
>    sscanf(other_buffer, "%d %d %d", &color, &price, &weight) =3D=3D 3 &&
>    needs_processing(color)
>    ) {
>      compute_volume(length, width, height);
>      compute_something_else(price, weight);
>  }

Personally, I dislike like if expressions that evaluate with side effects, I would
declare temps and move the scanfs outside the if statement.  It improves the 
readability too.

  I personally place the condition operator at the front, as William does, but
  nested.

   if ((pointer1 != NULL)
    && (pointer1->field7 == 0x152)) {
       return;
   }

scott
0
Reply scott 3/1/2010 6:12:43 PM

Julienne Walker <happyfrosty@hotmail.com> wrote:

> On Feb 24, 2:21=A0pm, Fred <fred.l.kleinschm...@boeing.com> wrote:
> > On Feb 24, 11:10=A0am, Julienne Walker <happyfro...@hotmail.com> wrote:
> > > On Feb 24, 1:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote=

> > > > 4. Does anyone care where the pointer * is? I prefer keeping to next =
> > > > to the type, rather than next to the variable name.
> >
> > > > EG. I like: char* firstName; and not so much: char *firstName;
> >
> > > Just make sure you're consistent and nobody will care. :-)
> >
> > Except that it is very error-prone to do so.
> 
> It's only error prone if you have multiple variables in a declaration
> statement (which the OP's example did not). That itself is often
> viewed as an unsafe practice.

Incorrectly. I would much rather see

  int   x,   y,   z;
  int *dx, *dy, *dz;

than

  int x;
  int y;
  int z;
  int* dx;
  int* dy;
  int* dz;

Richard

0
Reply raltbos (821) 3/1/2010 9:15:58 PM

On Mar 1, 4:15=A0pm, ralt...@xs4all.nl (Richard Bos) wrote:
> Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Feb 24, 2:21=3DA0pm, Fred <fred.l.kleinschm...@boeing.com> wrote:
> > > On Feb 24, 11:10=3DA0am, Julienne Walker <happyfro...@hotmail.com> wr=
ote:
> > > > On Feb 24, 1:35=3DA0pm, Poster Matt <postermatt@no_spam_for_me.org>=
 wrote=3D
> > > > > 4. Does anyone care where the pointer * is? I prefer keeping to n=
ext =3D
> > > > > to the type, rather than next to the variable name.
>
> > > > > EG. I like: char* firstName; and not so much: char *firstName;
>
> > > > Just make sure you're consistent and nobody will care. :-)
>
> > > Except that it is very error-prone to do so.
>
> > It's only error prone if you have multiple variables in a declaration
> > statement (which the OP's example did not). That itself is often
> > viewed as an unsafe practice.
>
> Incorrectly. I would much rather see

I'm sorry you disagree. Perhaps if you made it clear to everyone in
the world what you'd rather see, they'll change their beliefs to suit
your style. ;-)
0
Reply happyfrosty (97) 3/1/2010 9:32:42 PM

Julienne Walker wrote:
> On Mar 1, 4:15 pm, ralt...@xs4all.nl (Richard Bos) wrote:
>> Julienne Walker <happyfro...@hotmail.com> wrote:
>>> On Feb 24, 2:21=A0pm, Fred <fred.l.kleinschm...@boeing.com> wrote:
>>>> On Feb 24, 11:10=A0am, Julienne Walker <happyfro...@hotmail.com> wrote:
>>>>> On Feb 24, 1:35=A0pm, Poster Matt <postermatt@no_spam_for_me.org> wrote=
>>>>>> 4. Does anyone care where the pointer * is? I prefer keeping to next =
>>>>>> to the type, rather than next to the variable name.
>>>>>> EG. I like: char* firstName; and not so much: char *firstName;
>>>>> Just make sure you're consistent and nobody will care. :-)
>>>> Except that it is very error-prone to do so.
>>> It's only error prone if you have multiple variables in a declaration
>>> statement (which the OP's example did not). That itself is often
>>> viewed as an unsafe practice.
>> Incorrectly. I would much rather see
> 
> I'm sorry you disagree. Perhaps if you made it clear to everyone in
> the world what you'd rather see, they'll change their beliefs to suit
> your style. ;-)

Eh?  He did!

-- 
Ian Collins
0
Reply ian-news (9878) 3/1/2010 9:50:43 PM

On 3/1/2010 4:32 PM, Julienne Walker wrote:
> On Mar 1, 4:15 pm, ralt...@xs4all.nl (Richard Bos) wrote:
>> Julienne Walker<happyfro...@hotmail.com>  wrote:
>>> On Feb 24, 2:21=A0pm, Fred<fred.l.kleinschm...@boeing.com>  wrote:
>>>> On Feb 24, 11:10=A0am, Julienne Walker<happyfro...@hotmail.com>  wrote:
>>>>> On Feb 24, 1:35=A0pm, Poster Matt<postermatt@no_spam_for_me.org>  wrote=
>>>>>> 4. Does anyone care where the pointer * is? I prefer keeping to next =
>>>>>> to the type, rather than next to the variable name.
>>
>>>>>> EG. I like: char* firstName; and not so much: char *firstName;
>>
>>>>> Just make sure you're consistent and nobody will care. :-)
>>
>>>> Except that it is very error-prone to do so.
>>
>>> It's only error prone if you have multiple variables in a declaration
>>> statement (which the OP's example did not). That itself is often
>>> viewed as an unsafe practice.
>>
>> Incorrectly. I would much rather see
>
> I'm sorry you disagree. Perhaps if you made it clear to everyone in
> the world what you'd rather see, they'll change their beliefs to suit
> your style. ;-)

     I'm with Richard on this one.  When you have a bunch of
"obviously related" variables of the same type, there's little to
be gained and something to be lost by strewing the declarations
over multiple lines.

	double rx, ry, rz;  /* position */
	double vx, vy, vz;  /* velocity */
	double ax, ay, az;  /* acceleration */

.... is, to my eye, a lot more readable than

	/* position */
	double rx;
	double ry;
	double rz;
	/* velocity */
	double vx;
	double vy;
	double vz;
	/* acceleration */
	double ax;
	double ay;
	double az;

     Even when there are only two variables

	int compare(const void *pp, const void *qq) {
	    const struct jimjam *p = pp, *q = qq;

.... seems preferable to the one-per-line alternative: It moves
briskly past the boiler-plate preliminaries and helps the
attention proceed to the business at hand.

     On the other hand, I'd agree that

	int count, statusflag, i, modelnumber, j, k, errno_save;

.... is objectionable.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Reply esosman2 (2945) 3/1/2010 10:17:50 PM

In article <vsTin.1958$qi1.782@news.usenetserver.com>,
Scott Lurndal <slp53@pacbell.net> wrote:
>Personally, I dislike like if expressions that evaluate with side
>effects, I would
>declare temps and move the scanfs outside the if statement.  It improves the 
>readability too.

But that was not the point; the point was to make the if condition too
large to fit on a single line. The expressions were chosen more or less
at random just to illustrate that point.
0
Reply ike5 (222) 3/1/2010 11:24:00 PM

On 1 Mar, 21:50, Ian Collins <ian-n...@hotmail.com> wrote:
> Julienne Walker wrote:

> > I'm sorry you disagree. Perhaps if you made it clear to everyone in
> > the world what you'd rather see, they'll change their beliefs to suit
> > your style. ;-)
>
> Eh? =A0He did!

some people think there's a world outside clc!

0
Reply nick_keighley_nospam (4574) 3/2/2010 8:28:48 AM

On 27 Feb, 17:50, Casper H.S. Dik <Casper....@Sun.COM> wrote:
> Nick Keighley <nick_keighley_nos...@hotmail.com> writes:
> >On 27 Feb, 13:56, Casper H.S. Dik <Casper....@Sun.COM> wrote:
> >> i...@localhost.claranet.nl (Ike Naar) writes:
>
> >> Things I absolutely hate in some c-styles are:
>
> >> if(condition)
>
> >> "if" is a not a *function* it shouldn't look like one.
>
> >I write it like this
> > =A0 if (condition)
> > =A0 =A0 =A0 some_func (x);   /* <-- NOTE WELL */
>
> >and 'if' still doesn't look like a function to me
>
> It is fine with the space but not without (if() vs if ())


the point I was making was that I put the space in front of the
bracket BOTH for 'if' AND for a function invocation.
0
Reply nick_keighley_nospam (4574) 3/2/2010 8:32:00 AM

On 26 Feb 2010, Phil Carmody <thefatphil_demunged@yahoo.co.uk>
wrote: 

> Julienne Walker <happyfrosty@hotmail.com> writes:
>>> 4. Does anyone care where the pointer * is? I prefer keeping
>>> to next to the type, rather than next to the variable name.
>>>
>>> EG. I like: char* firstName; and not so much: char *firstName;
>>
>> Just make sure you're consistent and nobody will care. :-)
> 
> Horrifically wrong.

I think it's a good bet that Julienne meant that the OP should be 
consistent *with a reasonable style*.

> Just make sure you're consistent with
> everyone else, and nobody will care.

I don't know of any one style that's completely consistent with 
everyone else.

But overall, you make a good point, since abominations such as

  char    *
   foo(  char*
  *x    ) {
  /* ... */
              }

and

  void
   bar(  int*
   y    ) {
  /* ... */
              }

are consistent, but consistently awful.

-- 
"Don't worry about efficiency until you've attained correctness."
  ~ Eric Sosman, comp.lang.c
0
Reply dyer85 (333) 3/2/2010 9:53:55 AM

Eric Sosman <esosman@ieee-dot-org.invalid> writes:
>double rx, ry, rz;  /* position */
>double vx, vy, vz;  /* velocity */
>double ax, ay, az;  /* acceleration */
>... is, to my eye, a lot more readable than
>/* position */
>double rx;
>double ry;
>double rz;

  You can have your cake and eat it, too:

double rx; double ry; double rz; /* position */
double vx; double vy; double vz; /* velocity */
double ax; double ay; double az; /* acceleration */

0
Reply ram (2825) 3/2/2010 11:04:45 AM

On 24 Feb 2010, James Harris <james.harris.1@googlemail.com>
wrote: 

> On 24 Feb, 18:35, Poster Matt <postermatt@no_spam_for_me.org>
> wrote: 
>> Hi,
>>
>> I've a few questions concerning style when programming C on
>> UNIX systems. I don't want to look like an amateur. :)
> 
> As a fellow amateur in C....

Another fellow amateur, here.  :-)

>> 1. Having been programming in higher level languages for the
>> last 15 years, I'm finding it hard to get used to DEFINES in
>> all capitals. Is it really frowned on not to do so? Is
>> CamelCase acceptable? 
>>
>> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.
> 
> While I use them I don't like all caps for #defined values for
> two reasons
> 
> 1) #defined values don't seem to me too far removed from global
> parameters.

I'm not sure what you mean here by "global parameters".  Perhaps you 
mean object identifiers that have file scope?  If so, one crucial 
difference that stands out to me is that macros may not expand to 
lvalues.

  #define MaxFoo 512

  /* ... */

  int main(void)
  {
    /* ... */

    MaxFoo++; /* Whoops */

    /* ... */
  }

> Indeed if we change them to parameters in a function
> call they lose upper case status.

Again, I'm not sure what you mean.

> The two uses are similar. To
> my mind the format of the names should also be similar.
> 
> 2) I'd prefer to reserve all caps for macros. Then they serve as
> a warning that parameters are not guaranteed to be evaluated
> exactly once.

Another distinction is that you can't use macro identifiers exactly 
like function identifiers:

  qsort(data, nitems, sizeof *data, compar);

> Many libraries use all caps for their constants.

I rather like Rob Pike's style and reasoning behind identifiers in 
his _Notes on Programming in C_.

<http://www.lysator.liu.se/c/pikestyle.html>

<snip>

>> 4. Does anyone care where the pointer * is? I prefer keeping to
>> next to the type, rather than next to the variable name.
>>
>> EG. I like: char* firstName; and not so much: char *firstName;

I've occasionally seen:

  char * firstname;

> It's normally as the latter due to
> 
>  char* FirstName, ch, *p;
>  char *FirstName, ch, *p;

As Eric Sosman noted elsethread, I find that it depends on the 
context, whether or not I include multiple declarations on the same 
line.

I generally like to place the asterisk next to the declarator for 
object declarations.  For function prototypes and definitions, I 
like to place the asterisk next to the return type.

> Regardless of which form is used I think only ch will be a char
> variable

Right.

> - i.e. "char*" can be misleading.

I think mainly to newcomers, but I can't imagine it being too 
misleading for most C programmers.

<snip>

>> 5. On a slightly different note, I've been handling my error
>> messages by using #define string constants in a header file. I
>> saw some code which did this and it looked good to me. Is that
>> standard practise, if not what is? 
>>
>> EG. #define ErrorDirNotFound "The directory was not found."
> 
> That's much better than sprinkling messages throughout the code.
> If followed consistently it makes clear what messages the code
> can issue. Apart from clarity that would help if you ever want
> to release your code in another human language. There are better
> ways with more mechanism.

I believe some use enum constants, for example, as indexes for a 
lookup table with error message strings.

> You may need a way to include variable values in your messages.

Format strings for the *printf() functions is one obvious way.

>> There are so many style guides out there, most of them say
>> contradictory things at one point or another. What do the pros
>> do? 

As Julienne noted elsethread, the professionals are no more in 
agreement, with regard to style, than the differing style guides.

>> Finally, before someone points this out... I know if I'm coding
>> for myself, and not following somebody else's stylistic
>> requirements, I can do whatever I want. However I'd like my
>> code to be 'acceptable looking' to the wider UNIX C community. 
> 
> Check some examples: K&R2, C Unleashed, books by Douglas Comer,
> the Linux source etc. Also there is a FAQ entry for style
> issues: 
> 
>   http://c-faq.com/style/index.html

Also, I would imagine lurking in comp.unix.programmer would be 
another good way to pick up on common Unix coding styles, as well as 
good practices in general.

-- 
"Don't worry about efficiency until you've attained correctness."
  ~ Eric Sosman, comp.lang.c
0
Reply dyer85 (333) 3/2/2010 12:04:12 PM

On Mar 2, 7:04=A0am, Curtis Dyer <dye...@gmail.com> wrote:
> On 24 Feb 2010, James Harris <james.harri...@googlemail.com>
> wrote:
> > On 24 Feb, 18:35, Poster Matt <postermatt@no_spam_for_me.org>
> > wrote:
>
> > While I use them I don't like all caps for #defined values for
> > two reasons
>
> > 1) #defined values don't seem to me too far removed from global
> > parameters.
>
> I'm not sure what you mean here by "global parameters".

Most likely James meant the usual definition of a global variable in
C, which is an object with file scope and external linkage. But if
that's the case, and object macros are not too far removed from global
variables, we could make the same argument for literals, couldn't
we? ;-)

> > - i.e. "char*" can be misleading.
>
> I think mainly to newcomers, but I can't imagine it being too
> misleading for most C programmers.

I fail to see how char* x; is any more misleading than char *x;.
Either way the gotcha of char *x, y; still exists. Once you understand
the issue, it's a small matter of applying that knowledge. Of course,
char* x, *y; is pretty fugly, so the logical result is attaching to
the identifier in all cases (char *x, *y;), or splitting the
declarators across multiple statements: (char* x; char* y;).

Alternatively you could sidestep the issue with typedef:

typedef char* pchar;

pchar x, y;

Personally I'm not a fan of hiding levels of indirection behind a
typedef, but whatever floats your boat.

Ah, much ado about a trivial matter. Such is the way of clc. ^_^
0
Reply happyfrosty (97) 3/2/2010 1:30:51 PM

On 2 Mar, 12:04, Curtis Dyer <dye...@gmail.com> wrote:
> On 24 Feb 2010, James Harris <james.harri...@googlemail.com>
> > On 24 Feb, 18:35, Poster Matt <postermatt@no_spam_for_me.org>


> >> I've a few questions concerning style when programming C on
> >> UNIX systems. I don't want to look like an amateur. :)
>
> > As a fellow amateur in C....
>
> Another fellow amateur, here. =A0:-)
>
> >> 1. Having been programming in higher level languages for the
> >> last 15 years, I'm finding it hard to get used to DEFINES in
> >> all capitals. Is it really frowned on not to do so? Is
> >> CamelCase acceptable?
>
> >> EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

pre-processor macros have nasty semantics so its worth making them
standout.


> > While I use them I don't like all caps for #defined values for
> > two reasons
>
> > 1) #defined values don't seem to me too far removed from global
> > parameters.
>
> I'm not sure what you mean here by "global parameters". =A0

nor me. If he meant "global variable" the that means either file scope
with internal linkage or file scope with external linkage. I suppose
"global parameter" might be one of these.

int adjust =3D 10;

int make_adjustment (int fiddle)
{
     mass_adjust (adjust + fiddle);
}

void do_stuff (int bing)
{
    adjust =3D 0;
    make_adjustment ();
}


an abomination, but it happens (call backs without a needed parameter
are one excuse). I don't really see #defines as being like global
variables even though they have file scope.


> Perhaps you
> mean object identifiers that have file scope? =A0If so, one crucial
> difference that stands out to me is that macros may not expand to
> lvalues.
>
> =A0 #define MaxFoo 512
>
> =A0 /* ... */
>
> =A0 int main(void)
> =A0 {
> =A0 =A0 /* ... */
>
> =A0 =A0 MaxFoo++; /* Whoops */
>
> =A0 =A0 /* ... */
> =A0 }

well they can if you use them to alias an l-value

   int max_foo;
   #define MAXFOO max_foo

  MAXFOO++

not a good idea but...

> > Indeed if we change them to parameters in a function
> > call they lose upper case status.
>
> Again, I'm not sure what you mean.

me neither!


> > The two uses are similar.

which two uses!

> > To
> > my mind the format of the names should also be similar.
>
> > 2) I'd prefer to reserve all caps for macros. Then they serve as
> > a warning that parameters are not guaranteed to be evaluated
> > exactly once.

what? I thought you were explaining why you weren't using all caps for
macros?! Did you mean value macros and function-like macros?

#define MaxFoo 127
#define INC(X) (X++)


> Another distinction is that you can't use macro identifiers exactly
> like function identifiers:
>
> =A0 qsort(data, nitems, sizeof *data, compar);

why not? I just don't follow you.

<snip>

> >> 4. Does anyone care where the pointer * is?

oh yes! C programmers are nothing if not opinionated!

<snip>

> > - i.e. "char*" can be misleading.
>
> I think mainly to newcomers, but I can't imagine it being too
> misleading for most C programmers.

the C++ people seem to mange ok

<snip>

0
Reply nick_keighley_nospam (4574) 3/2/2010 2:03:16 PM

[snips]

On Mon, 01 Mar 2010 01:06:04 -0800, Nick Keighley wrote:

> one difficulty with embedded <tab-chars> as the only layout character is
> that you lose fine control.
> 
> void pippo (int n)
> {
>     if ((n == PHOTON) ||
>         (n == LEPTON) ||
>         (n == HADRON))
>     {
>         send_msg ("claim nobel!");
>     }
> }
> 
> I don't see how this layout can survive spaceless layout or variable tab
> stops. Presumably you don't require layout like this.

Frequently.  Here's a tip: indent the ( to a tab stop.  All lines up - 
and allows the individual viewer to work to his own preferences.

>> >> Contrast that to hitting delete on a line which uses spaces instead
>> >> of tabs.  All this does is mess up the formatting, as the editor is
>> >> almost certain to treat a space as a _space_, as it should, not as a
>> >> tab, which it _shouldn't_, because the character involved is not a
>> >> tab, but a space.
>>
>> > get a better editor
>>
>> I have a better editor.
> 
> :-)

Indeed.  The whole spaces-vs-tabs thing is one of those "Obviously, my 
way is superior, you heathen (heathfield?) infidel!" issues.

<snicker>


>> One that understands the difference between spaces and tabs.  One that
>> does *not* do something as brain-dead as deleting _multiple_ characters
>> when I press delete once.  Any editor which deletes multiple items on a
>> single delete simply cannot be trusted, it's liable to destroy
>> something.
> 
> no. My editor (this is actually a configurable option) only does this
> for spaces. I assure you it works well in practice.

I wouldn't trust any editor, regardless of configuration, which deleted 
multiple characters on a single "delete" keypress.  Too freaking 
dangerous to be used on anything more important than "to do" lists.

> If I want to insert <tab-chars> (eg. for the dreaded make file) I have
> to change an option on my editor. Normally I do not want to insert
> <tab-chars>

Wait, you have to _reconfigure_ your editor to insert tabs when you hit 
tab, because by default, pressing tab doesn't give you a tab, it gives 
you spaces?  What does spacebar give you?  Ampersands?  Lemme guess: 
"enter" activates "close file without saving".  And delete nukes anything 
from zero to 8 characters.


>> But then you're on my side of the
>> fence, with spaces being defective by design for indent.
> 
> this is phrasing it rather strongly. There are plenty of people who have
> a different opinion from you.

Yes, well, obviously, their opinion is wrong and silly-headed.  

(grin, duck, run)


>> If they weren't
>> defective by design, you wouldn't be using tab instead of space.
> 
> is that <tab-char> or <tab-key>?

Yes.  The tab key puts in tabs.  The spacebar puts in spaces.  Enter puts 
in enter, 'Q' puts in 'Q' and so forth.

> [it's getting repetitive]

Shall we do emacs versus vi next? ;)

>> If your editor - and the notion of spaces for indentation - weren't
>> defective by design, you wouldn't need to use a special key to insert
>> spaces; that's why you have a space bar.  The fact you have to resort
>> to something entirely different, the tab key, is prima facie evidence
>> the whole notion of spaces to indent is as defective as it appears.
> 
> this is opinion masquerading as fact.

Aren't all such "debates"?

The issue of "stylistic conventions", in the realm of C, is one of those 
cases where, beyond a few basic rules of thumb - all-upper-case for 
macros, for example - there are no universally agreed upon approaches, 
each with its adherents and detractors, each with its benefits and 
drawbacks.


>> Now, if your editor worked properly, using tabs instead of spaces, with
>> the tab key inserting tabs as it should, then when viewed on someone
>> else's display, rather than yours, it would show the code as *they*
>> prefer to view it, rather than as *you* have decided is the only true
>> way which everyone should be forced to view it in.
> 
> I like finer control over my layout than you do apparently

Quite the contrary.  I like delete to delete _one_ character, tab to 
insert a tab, and so forth.  Not quasi-random side-effects.

>> Really, isn't this just a case of imposing your own layout conventions
>> on others, rather than using a common sense approach which actually
>> lets everyone view the code in their own preferred manner?  Without
>> having to defeat the needless additional complication of converting
>> some godawful arrangement you happen to like into something actually
>> manageable?
> 
> but you also require others to agree to your conventions.

Not really; at least my approach allows them to layout their code to 
their visual preferences, without mucking it up for everyone else.


> I bet you'd hate this approach
> 
> Code laid out like this with 4 character indent xxxx
>     yyyy
>         zzzz
>             wwww
> 
> and using S and T to represent the "layout charcaters" actually looked
> like this
> 
> xxxx
> SSSSyyyy
> Tzzzz
> TSSSSwwww

Blech.  Why do that?  Use tabs for indent, the way they're intended.

> the worst or all possible worlds!

No, the worst of all possible worlds would be having to be a maintenance 
coder for Jeff Relf's magical news client. :)

0
Reply kbjarnason (4583) 3/2/2010 2:45:14 PM

ram@zedat.fu-berlin.de (Stefan Ram) wrote:

> Eric Sosman <esosman@ieee-dot-org.invalid> writes:
> >double rx, ry, rz;  /* position */
> >double vx, vy, vz;  /* velocity */
> >double ax, ay, az;  /* acceleration */
> >... is, to my eye, a lot more readable than
> >/* position */
> >double rx;
> >double ry;
> >double rz;
> 
>   You can have your cake and eat it, too:
> 
> double rx; double ry; double rz; /* position */
> double vx; double vy; double vz; /* velocity */
> double ax; double ay; double az; /* acceleration */

Yes, there's always _someone_ who prefers the worst of both worlds.

Richard
0
Reply raltbos (821) 3/2/2010 3:08:27 PM

Kelsey Bjarnason <kbjarnason@gmail.com> writes:
>Frequently.  Here's a tip: indent the ( to a tab stop.  All lines up - 
>and allows the individual viewer to work to his own preferences.

  The text

Talphabeta(T(
TTT(

  , where �T� denotes a tab charater, will be rendered as

       alphabeta(      (
                       (

  , when there are tab positions at 8, 16, 24, 32, and so on.
  So now, the final parentheses of every line are aligned.

  But with tab positions at 4, 8, 12, 16, 20, and so on, it
  will be rendered as 

   alphabeta(  (
           (

  So it is not possible to align characters of a line that
  are not the first non-tab character of a line using tabs
  in such a way that they will be aligned for every tab width.

0
Reply ram (2825) 3/2/2010 3:13:46 PM

"Kelsey Bjarnason" <kbjarnason@gmail.com> wrote in message 
news:m7ydnd62sLPnuRDWnZ2dnUVZ_tAAAAAA@giganews.com...
> On Mon, 01 Mar 2010 01:06:04 -0800, Nick Keighley wrote:

>> If I want to insert <tab-chars> (eg. for the dreaded make file) I have
>> to change an option on my editor. Normally I do not want to insert
>> <tab-chars>
>
> Wait, you have to _reconfigure_ your editor to insert tabs when you hit
> tab, because by default, pressing tab doesn't give you a tab, it gives
> you spaces?  What does spacebar give you?  Ampersands?  Lemme guess:
> "enter" activates "close file without saving".  And delete nukes anything
> from zero to 8 characters.

On my typewriter, Tab moves the carriage up to the next tab-stop. Backspace 
moves the carriage back, one space at a time.

So Tab is just a kind of macro on that machine.

To emulate the same behaviour in an editor, you don't want or need to store 
actual tab characters, you just need the ability to quickly skip forward or 
back to the next tab-stop position.

But one problem is ensuring the same set of tab-stops are used across 
editors, or even across files in the same editor.


> Yes.  The tab key puts in tabs.  The spacebar puts in spaces.  Enter puts
> in enter, 'Q' puts in 'Q' and so forth.

Printable characters tend to be inserted into the text. Non-printable chars 
and special keys could do anything. I suppose Esc puts in escape characters 
and F1 puts in 'F1' characters?

-- 
Bart

0
Reply bartc (783) 3/2/2010 3:46:52 PM

[snips]

On Tue, 02 Mar 2010 15:13:46 +0000, Stefan Ram wrote:

>   So it is not possible to align characters of a line that are not the
>   first non-tab character of a line using tabs in such a way that they
>   will be aligned for every tab width.

And thus, we have a conclusive argument for using spaces, which are 
guaranteed never to work for any setup but the original author's, *and* 
fail in a way virtually impossible to recover from?

Missed a step there, I think. :)

0
Reply kbjarnason (4583) 3/2/2010 6:45:50 PM

Rich Webb <bbew.ar@mapson.nozirev.ten> writes:

> On Wed, 24 Feb 2010 11:10:21 -0800 (PST), Julienne Walker
> <happyfrosty@hotmail.com> wrote:
>
>>On Feb 24, 1:35 pm, Poster Matt <postermatt@no_spam_for_me.org> wrote:
>>> Hi,
>>>
>>> I've a few questions concerning style when programming C on UNIX systems. I
>>> don't want to look like an amateur. :)
>
>>> 3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
>>> 120 chars I start thinking this might not look great in someone else's editor.
>>
>>I try to keep each line under 100 characters (80 if possible). It's
>>less about monitor size than it is about easily reading my code at a
>>glance.
>
> Typographers, who study this thing with the fervor that programmers
> bring to brace styles, would tend to agree. There are always reasonable
> exceptions but a line length that's 70-80 characters (monospaced) seems
> to be a sweet spot for comprehension.

Granted (well more or less), but notice that there is an
important difference.  The reading mode for prose (ordinary
written text) is very different than the reading mode for
program source.  Source code is not read as a single linear
text;  it chunkifies into very particular units, and these
units are more easily comprehended when grouped in some
spatial patterns than others.

Not to say that I disagree with the conclusion necessarily, the
number 80 may be right for both.  But it's a mistake to think
that the same reasoning must apply to both domains, because
the reading modes in those respective domains are so different.
0
Reply txr2511 (42) 3/3/2010 12:50:36 AM

Ben Bacarisse <ben.usenet@bsb.me.uk> writes:

> Richard Heathfield <rjh@see.sig.invalid> writes:
>
>> Anand Hariharan wrote:
>> <snip>
>>
>>> Haven't seen anyone point this out:
>>>
>>> Rather than -
>>>
>>>   #define MAXNUMFILES 1024
>>>
>>> - prefer -
>>>
>>>   const int MaxNumFiles = 1024;
>>>
>>>
>>> That way your preprocessor won't do as much damage.
>>
>> Fine in C99, I think, but an issue in C90 if he's using it to define
>> an array size.
>
> It's a problem in C99 too, if the array is defined at file scope or it
> has internal linkage.  There are other reasons why it's not a great
> idea in C99.  They stem from the fact that MaxNumFiles is not
> permitted as part of a constant expression.  [snip elaboration]

Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
expression, albeit an implementation-specific constant expression;
it just isn't _required_ to be a portable constant expression.
0
Reply txr2511 (42) 3/3/2010 12:54:50 AM

"robertwessel2@yahoo.com" <robertwessel2@yahoo.com> writes:

> On Feb 25, 11:15 pm, Kelsey Bjarnason <kbjarna...@gmail.com> wrote:
>> On Thu, 25 Feb 2010 19:48:06 -0800, Ben Pfaff wrote:
>> > Kelsey Bjarnason <kbjarna...@gmail.com> writes:
>>
>> >> My take on this has always been to standardize the format "checked in",
>> >> then use indent or some equivalent, on check in and check out, to
>> >> convert between the "checkin format" and the individual coder's
>> >> preferred format.
>>
>> > I've heard of this approach, but I always assumed that it was a joke.
>> > You really use it?
>>
>> I have, repeatedly, over the years.
>>
>> The problem with _not_ doing it is that you tend to get a lot of checkins
>> where the "diff" is wildly out of sync with what actually got changed,
>> particularly if the coder's tools do things such as switching tabs to
>> spaces or re-organizing braces, etc, etc, etc, which many tools do.
>>
>> By using indent or an equivalent on checkin, you ensure a standard format
>> going in, such that only "real" changes are recorded, and by using it on
>> checkout, you deliver to the coder whatever flavour he's happiest with.
>>
>> Or, you can skip it on checkout and just let him use whatever tools he
>> likes, but I've found delivering to the developer something which he is
>> maximally comfortable with, right out of the gate, tends to produce
>> maximum productivity and minimum frustration.
>
>
> A problem with that approach is that it will trash any special/careful
> formatting that you might use to clarify a complex section of code.
> [snip]

Perhaps it will if the tool is poor, but it doesn't have to.
Certainly indent-like tools can be written that don't just
disregard all white space but filter it in or out selectively,
doing just enough to make the indentation and brace placement
right but still preserving column alignments appropriately when
the input warrants it.

The benefits of having such a tool, especially for a large group,
clearly outweigh the cost of providing it.
0
Reply txr2511 (42) 3/3/2010 1:10:03 AM

Tim Streater <timstreater@waitrose.com> writes:

> On 26/02/2010 02:56, Kelsey Bjarnason wrote:
>> On Wed, 24 Feb 2010 22:09:43 +0000, Scott Lurndal wrote:
>>
>>> James Harris<james.harris.1@googlemail.com>  writes:
>>>> On 24 Feb, 20:53, BruceS<bruce...@hotmail.com>  wrote:
>>>>
>>>> ...
>>>>
>>>>> I would like to add that, as long as you're trying to use good style,
>>>>> for God's sake don't use the wrong indentation style. =A0If you put
>>>>> your opening braces on the same line as your conditional, you'll just
>>>>> look like a fool in front of your friends and colleagues.
>>>>
>>>> Snobbish nonsense!
>>>>
>>>>
>>>>
>>> Indeed.
>>>
>>>     if (condition) {
>>>
>>> is preferred over
>>>
>>>     if (condition)
>>>     {
>>
>> Not by me, it ain't. :)
>>
>>> Makes it much more likely that a properly written function will fit on a
>>> single page/screen.
>>
>> And less likely to catch proper vs improper bracing and indentation, when
>> the braces don't line up with the indents.
>>
>>> In 30 years of C programming, no employer or project has used the latter
>>> form.
>>
>> This is one of those cases where there really are legitimate reasons for
>> each approach, with the deciding factor being preference.
>>
>> My take on this has always been to standardize the format "checked in",
>> then use indent or some equivalent, on check in and check out, to convert
>> between the "checkin format" and the individual coder's preferred format.
>
> My preferred approach is to do like this:
>
> function wiggy ()
>      {
>      if (cond)
>           {
>           dostuff;
>           }
>      else {
>           dootherstuff;
>           }
>      }
>
> This has been my approach ever since I was writing BCPL in the 70s -
> it has the braces lining up so that the matching can be seen easily.

Does this mean you've never tried alternate approaches since then?
Did you try any other approaches earlier?
0
Reply txr2511 (42) 3/3/2010 1:11:40 AM

Tim Woodall <devnull@woodall.me.uk> writes:

> [snip various comments on brace placement]
>
> Obviously, the major advantage to putting the '{' on the same line as
> the conditional is that it reduces paper usage when typesetting

Certainly this could count as an advantage, but it is not "the
major" advantage, or an especially important one.

> and hence why you will normally see it in books.

K&R uses the same bracing style, AFAIAA, that Ken Thompson
and Dennis Ritchie use in their own programming.  I expect
most people use in their books the same style that they
use themselves when programming.  And there are plenty of
books that put open braces on separate lines rather than
on the same lines as if, etc.
0
Reply txr2511 (42) 3/3/2010 1:20:40 AM

Ben Pfaff <blp@cs.stanford.edu> writes:

> Kelsey Bjarnason <kbjarnason@gmail.com> writes:
>[snip]
>
>> By using indent or an equivalent on checkin, you ensure a standard format 
>> going in, such that only "real" changes are recorded, and by using it on 
>> checkout, you deliver to the coder whatever flavour he's happiest with.
>
> Doesn't it screw up any careful formatting, e.g. of comments?
> And sometimes careful placement of white space can make the code
> much easier to read.

Better indent-style tools will preserve such extra formatting
and/or alignments in the reformatted source.  Obviously this
can't be done to work in every imaginable situation, but IME
the coverage of different scenarios can be good enough so that
the limitations are felt hardly ever if at all.  Not perfect,
but practically speaking good enough (and much better than
some of the more restrictive alternatives).
0
Reply txr2511 (42) 3/3/2010 1:31:31 AM

Tim Rentsch wrote:
> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
> 
>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>
>>> Anand Hariharan wrote:
>>> <snip>
>>>
>>>> Haven't seen anyone point this out:
>>>>
>>>> Rather than -
>>>>
>>>>   #define MAXNUMFILES 1024
>>>>
>>>> - prefer -
>>>>
>>>>   const int MaxNumFiles = 1024;
>>>>
>>>>
>>>> That way your preprocessor won't do as much damage.
>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>> an array size.
>> It's a problem in C99 too, if the array is defined at file scope or it
>> has internal linkage.  There are other reasons why it's not a great
>> idea in C99.  They stem from the fact that MaxNumFiles is not
>> permitted as part of a constant expression.  [snip elaboration]
> 
> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
> expression, albeit an implementation-specific constant expression;
> it just isn't _required_ to be a portable constant expression.

What?  You could say just about any nonsense is permitted as part of an 
implementation-specific expression.

That doesn't alter that fact that in C90 or C99, MaxNumFiles is not 
permitted as part of a constant expression.

-- 
Ian Collins
0
Reply ian-news (9878) 3/3/2010 1:38:28 AM

Ian Collins <ian-news@hotmail.com> writes:
> Tim Rentsch wrote:
>> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>> Anand Hariharan wrote:
>>>> <snip>
>>>>> Haven't seen anyone point this out:
>>>>>
>>>>> Rather than -
>>>>>
>>>>>   #define MAXNUMFILES 1024
>>>>>
>>>>> - prefer -
>>>>>
>>>>>   const int MaxNumFiles = 1024;
>>>>>
>>>>>
>>>>> That way your preprocessor won't do as much damage.
>>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>>> an array size.
>>> It's a problem in C99 too, if the array is defined at file scope or it
>>> has internal linkage.  There are other reasons why it's not a great
>>> idea in C99.  They stem from the fact that MaxNumFiles is not
>>> permitted as part of a constant expression.  [snip elaboration]
>>
>> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
>> expression, albeit an implementation-specific constant expression;
>> it just isn't _required_ to be a portable constant expression.
>
> What?  You could say just about any nonsense is permitted as part of
> an implementation-specific expression.
>
> That doesn't alter that fact that in C90 or C99, MaxNumFiles is not
> permitted as part of a constant expression.

I think Tim is referring to C99 6.6p10:

    An implementation may accept other forms of constant expressions.

(I just noticed that this doesn't use the term
"implementation-defined" implying, I think, that an implementation
can accept other forms of constant expressions but isn't required
to document them.)

My understanding is that code that uses extensions in general (as
permitted by C99 4p6) still require diagnostics if the code violates a
constraint, but code that uses "other forms of constant expressions"
does not.

I'd say Tim's statement is correct, but I'd place the emphasis very
differently: MaxNumFiles is not permitted as part of a constant
expression (unless the implementation permits it under C99 6.6p10).

Are there any real-world C implementations that take advantage of this
permission?  Specifically, is there a C compiler that accepts
additional forms of constant expressions in (what it claims to be)
conforming mode?

And why is that permission there in the first place?  What benefit
does it really provide beyond the existing permission to provide
extensions?

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/3/2010 2:02:15 AM

On 2010-02-26 23:54:08 +0000, Richard said:
> 
> because it does the same thing in one line less with ZERO reduction in
> readability.

I find there is zero reduction in readability in that style, ergo 
everyone must find that there is zero reduction in readability.

Anyway with that coding style you end up with this abomination:

if(x == 0) {
    // blah
} else if(x == 1) {
   // blah
} else {
   // blah
}

Go, go Java coding standards!

0
Reply blah8398 (1) 3/3/2010 4:25:21 AM

Nizumzen <blah@mcnuggets.com> writes:
> On 2010-02-26 23:54:08 +0000, Richard said:
>> because it does the same thing in one line less with ZERO reduction in
>> readability.
>
> I find there is zero reduction in readability in that style, ergo
> everyone must find that there is zero reduction in readability.
>
> Anyway with that coding style you end up with this abomination:
>
> if(x == 0) {
>    // blah
> } else if(x == 1) {
>   // blah
> } else {
>   // blah
> }

Here's how I would write the above:

if (x == 0) {
    // blah
}
else if (x == 1) {
    // blah
}
else {
    // blah
}

In my preferred style, a closing brace appears on a line by itself, or
possibly followed by a comment.  Some people like to put "else" on the
same line as the preceding "}"; I don't.

I don't suggest that everyone needs to code this way.  Nor do I
suggest that any consistent style is an "abomination".

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/3/2010 4:42:17 AM

Scott Lurndal wrote:
>   I personally place the condition operator at the front, as William does, but
>   nested.
> 
>    if ((pointer1 != NULL)
>     && (pointer1->field7 == 0x152)) {
>        return;
>    }

if ( ( pointer1 =! NULL )
      && ( pointer1->field7 = 0x152 ) ) {
         return;
     }

ops && ops
0
Reply vladaspams2 (160) 3/3/2010 8:21:44 AM

"Poster Matt" <postermatt@no_spam_for_me.org> ha scritto nel messaggio
news:ujehn.44277$Ym4.21796@text.news.virginmedia.com...
> Hi,
>
> I've a few questions concerning style when programming C on UNIX systems. I
> don't want to look like an amateur. :)

all code here came from the poster "Peter Nilsson" from
news:f6245590-e586-4cb0-88f8-37afcebe15d4@s25g2000prd.googlegroups.com

so you say the professional coder style
  #include <string.h>
  #include <stdlib.h>

  static char *replace2_search
    (
      size_t n,
      const char *s,
      const char *p, size_t pz,
      const char *q, size_t qz
    )
  {
    const char *f;
    size_t z;
    char *r;

    if (pz == 0 || !(f = strstr(s, p)))
    {
      z = strlen(s);
      r = malloc(n + z + 1);
      if (r) strcpy(r + n, s);
    }
    else
    {
      z = f - s;
      r = replace2_search(n + z + qz, f + pz, p, pz, q, qz);
      if (r)
      {
        memcpy(r + n, s, z);
        memcpy(r + n + z, q, qz);
      }
    }

    return r;
  }

  char *replace2(const char *s, const char *p, const char *q)
  {
    return replace2_search(0, s, p, strlen(p), q, strlen(q));
  }

that can not be seen in my monitor editor,
here too in the editor of the news
is better than my amatorish stile
#include <string.h>
#include <stdlib.h>

char* replace2_search(size_t n, char*  s,
                      char*  p, size_t pz,
                      char*  q, size_t qz )
{char *f, *r;
 size_t    z;
 if(pz==0 || !(f = strstr(s, p)))
    {z= strlen(s); r= (char*) malloc(n+z+1);
     if(r)
        strcpy(r+n, s);
    }
 else
    {z= f-s;
     r= replace2_search(n+z+qz, f+pz, p, pz, q, qz);
     if(r){memcpy(r+n,   s,  z);
           memcpy(r+n+z, q, qz);
          }
    }
 return r;
}

char*   replace2(char *s, char *p, char *q)
{if(s==0||p==0||q==0)  return  0;
 return replace2_search(0, s, p, strlen(p), q, strlen(q));
}

that can be seen in one aye shot




0
Reply io_x 3/3/2010 9:11:34 AM

On 03/03/2010 01:11, Tim Rentsch wrote:
> Tim Streater<timstreater@waitrose.com>  writes:

>> My preferred approach is to do like this:
>>
>> function wiggy ()
>>       {
>>       if (cond)
>>            {
>>            dostuff;
>>            }
>>       else {
>>            dootherstuff;
>>            }
>>       }
>>
>> This has been my approach ever since I was writing BCPL in the 70s -
>> it has the braces lining up so that the matching can be seen easily.
>
> Does this mean you've never tried alternate approaches since then?
> Did you try any other approaches earlier?

I didn't use any such structured language before then. Well, that's not 
quite true. We had Algol, Snobol, Lisp and perhaps some others on my 
post-grad CS course in the late 60s, but I went to CERN after that where 
everything was, perforce, FORTRAN.


-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/3/2010 9:46:30 AM

On 02 Mar 2010, Nick Keighley <nick_keighley_nospam@hotmail.com>
wrote: 

> On 2 Mar, 12:04, Curtis Dyer <dye...@gmail.com> wrote:
>> On 24 Feb 2010, James Harris <james.harri...@googlemail.com>
>> > On 24 Feb, 18:35, Poster Matt <postermatt@no_spam_for_me.org>

<snip>

>> Perhaps you
>> mean object identifiers that have file scope? �If so, one
>> crucial difference that stands out to me is that macros may not
>> expand to lvalues.

<snip code example>

> well they can if you use them to alias an l-value
> 
>    int max_foo;
>    #define MAXFOO max_foo
> 
>   MAXFOO++
> 
> not a good idea but...

Right, that's why I said, "...macros *may* not expand to 
lvalues."  Although, I could have stated more clearly, it depends 
on the macro's definition.

<snip>

>> Another distinction is that you can't use macro identifiers
>> exactly like function identifiers:
>>
>> � qsort(data, nitems, sizeof *data, compar);
> 
> why not? I just don't follow you.

I don't follow me, either.  Unfortunately, I must have written 
that qsort() example too long after I wrote the paragraph above 
it, and missed making my own point in the process.  Sorry about 
that.

Here's a better example illustrating what I meant:

  /* potentially misleading macro */
  #define foobar(x) \
    do { \
      /* ... */ \
    } while (0)

  /* ... */

  foobitize(someobject, foobar);

I realize this is very contrived, but something to this effect is 
what I originally intended to demonstrate.

<snip>

-- 
"Don't worry about efficiency until you've attained correctness."
  ~ Eric Sosman, comp.lang.c
0
Reply dyer85 (333) 3/3/2010 11:33:13 AM

io_x wrote:
> 
> "Poster Matt" <postermatt@no_spam_for_me.org> ha scritto nel messaggio
> news:ujehn.44277$Ym4.21796@text.news.virginmedia.com...
> > Hi,
> >
> > I've a few questions concerning style
> > when programming C on UNIX systems. I
> > don't want to look like an amateur. :)
> 
> all code here came from the poster "Peter Nilsson" from
> news:f6245590-e586-4cb0-88f8-37afcebe15d4@s25g2000prd.googlegroups.com
> 
> so you say the professional coder style
>   #include <string.h>
>   #include <stdlib.h>
> 
 
> that can not be seen in my monitor editor,
> here too in the editor of the news
> is better than my amatorish stile
 
> char*   replace2(char *s, char *p, char *q)
> {if(s==0||p==0||q==0)  return  0;
>  return replace2_search(0, s, p, strlen(p), q, strlen(q));
> }
> 
> that can be seen in one aye shot

Real programmers typically write programs that can't
all fit on a screen display.  
With that in mind, they write in such a way so that 
whatever can be displayed on a screen, is easiest to read.

You personally io_x, 
will never write a program that can't all fit on one screen.

-- 
pete
0
Reply pfiland (6613) 3/3/2010 11:47:04 AM

On 02 Mar 2010, Julienne Walker <happyfrosty@hotmail.com> wrote:

> On Mar 2, 7:04�am, Curtis Dyer <dye...@gmail.com> wrote:
>> On 24 Feb 2010, James Harris <james.harri...@googlemail.com>
>> wrote:

<snip>

>> > - i.e. "char*" can be misleading.
>>
>> I think mainly to newcomers, but I can't imagine it being too
>> misleading for most C programmers.
> 
> I fail to see how char* x; is any more misleading than char *x;.
> Either way the gotcha of char *x, y; still exists.

Right, but visually, "char *x, y" more clearly demonstrates what 
the declaration actually means.  Realistically though, I doubt it 
would be an issue for anyone, say, past their first week of 
learning C.

<snip>

> Alternatively you could sidestep the issue with typedef:
> 
> typedef char* pchar;
> 
> pchar x, y;
> 
> Personally I'm not a fan of hiding levels of indirection behind
> a typedef, but whatever floats your boat.

Nor am I, but Microsoft sure seems to be found of that style.

> Ah, much ado about a trivial matter. Such is the way of clc. ^_^

But discussions about good style is Serious Business. :-)

-- 
"Don't worry about efficiency until you've attained correctness."
  ~ Eric Sosman, comp.lang.c
0
Reply dyer85 (333) 3/3/2010 11:56:52 AM

On Mar 3, 6:56=A0am, Curtis Dyer <dye...@gmail.com> wrote:
> On 02 Mar 2010, Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Mar 2, 7:04 am, Curtis Dyer <dye...@gmail.com> wrote:
> >> On 24 Feb 2010, James Harris <james.harri...@googlemail.com>
> >> wrote:
>
> >> > - i.e. "char*" can be misleading.
>
> >> I think mainly to newcomers, but I can't imagine it being too
> >> misleading for most C programmers.
>
> > I fail to see how char* x; is any more misleading than char *x;.
> > Either way the gotcha of char *x, y; still exists.
>
> Right, but visually, "char *x, y" more clearly demonstrates what
> the declaration actually means. =A0Realistically though, I doubt it
> would be an issue for anyone, say, past their first week of
> learning C.

That's my opinion as well. I've helped a *lot* of beginners over the
years, and at the moment I can't recall a single instance where there
was a problem due to the "misleading" placement of an asterisk. Common
problems tend to be independently discovered by virtually every
beginner, so I'm inclined to say that it's not really the big problem
that some paint it out to be.

> > Ah, much ado about a trivial matter. Such is the way of clc. ^_^
>
> But discussions about good style is Serious Business. :-)

Not serious enough to warrant endless debate. Bracing styles, tabs vs.
spaces, indentation amount, it's all subjective. As long as a
reasonable style is used, it's not going to seriously impede one's
ability to read code using that style.
0
Reply happyfrosty (97) 3/3/2010 1:27:46 PM

pete <pfiland@mindspring.com> writes:

>io_x wrote:

>> char*   replace2(char *s, char *p, char *q)
>> {if(s==0||p==0||q==0)  return  0;
>>  return replace2_search(0, s, p, strlen(p), q, strlen(q));
>> }
>> 
>> that can be seen in one aye shot

>Real programmers typically write programs that can't
>all fit on a screen display.  
>With that in mind, they write in such a way so that 
>whatever can be displayed on a screen, is easiest to read.

>You personally io_x, 
>will never write a program that can't all fit on one screen.

His style is best known for the "Obfuscated C Code Contest" :-)

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/3/2010 1:57:12 PM

Vladimir Jovic <vladaspams@gmail.com> writes:
> Scott Lurndal wrote:
>>   I personally place the condition operator at the front, as
>>   William does, but nested.
>>
>>    if ((pointer1 != NULL)
>>     && (pointer1->field7 == 0x152)) {
>>        return;
>>    }
>
> if ( ( pointer1 =! NULL )
>      && ( pointer1->field7 = 0x152 ) ) {
>         return;
>     }
>
> ops && ops

if ( pointer1 != NULL &&
     pointer1->field7 == 0x152 )
{
    return;
}

I put the opening brace on the same line as the "if" if it fits.
If it doesn't, I put it on a line by itself, so it doesn't get lost.
It's probably not entirely consistent, but it works well for me.

Note that I also dropped some extraneous parentheses.  Too many
parentheses can be as confusing as too few, and I think it's
sufficiently obvious that "==" and "!=" bind more tightly than "&&".
The alignment of the subexpressions helps.

I do not suggest that my style is the only correct one.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/3/2010 5:55:02 PM

On Mar 3, 7:55=A0pm, Keith Thompson <ks...@mib.org> wrote:
>
> Note that I also dropped some extraneous parentheses. =A0Too many
> parentheses can be as confusing as too few,
>
I use the rule of three. Three levels of indirection, three dimensions
in an array, or three nested parentheses. (Some people will realise
that threse are different ways of saying the same thing).


0
Reply malcolm.mclean5 (721) 3/3/2010 6:18:35 PM

Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Mar 3, 7:55 pm, Keith Thompson <ks...@mib.org> wrote:
>> Note that I also dropped some extraneous parentheses.  Too many
>> parentheses can be as confusing as too few,
>>
> I use the rule of three. Three levels of indirection, three dimensions
> in an array, or three nested parentheses. (Some people will realise
> that threse are different ways of saying the same thing).

I agree, mostly, that more than three levels of nested parentheses can
be confusing.  I'm not convinced there should be a hard limit, or that
three is the right number, but I won't argue the point; you could well
be right about that.

But the code in question here only had two levels of nested
parentheses:

    if ( ( pointer1 != NULL ) &&
         ( pointer1->field7 == 0x152 ) )
    ...

That's not an unreasonable depth of nesting, but IMHO the inner
parentheses still do nothing to aid legibility.  I find this:

    if ( pointer1 != NULL &&
         pointer1->field7 == 0x152 )
    ...

or even this:

    if ( pointer1 != NULL && pointer1->field7 == 0x152 )
    ...

easier to read and understand.

The point is that the number of levels of nesting shouldn't be the
*only* criterion for determining that a piece of code is difficult
to read.

The expression in question here is relatively simple.  In more complex
cases, code layout can aid legibility -- or hurt it if the layout
doesn't reflect the logical structure of the code:

    if( pointer1 !=
            NULL&&pointer1->
                field7
        == 0x152)

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/3/2010 7:46:20 PM

Keith Thompson wrote:
> Vladimir Jovic <vladaspams@gmail.com> writes:
>> Scott Lurndal wrote:
>>>   I personally place the condition operator at the front, as
>>>   William does, but nested.
>>>
>>>    if ((pointer1 != NULL)
>>>     && (pointer1->field7 == 0x152)) {
>>>        return;
>>>    }
>> if ( ( pointer1 =! NULL )
>>      && ( pointer1->field7 = 0x152 ) ) {
>>         return;
>>     }
>>
>> ops && ops
> 
> if ( pointer1 != NULL &&
>      pointer1->field7 == 0x152 )
> {
>     return;
> }
> 
> I put the opening brace on the same line as the "if" if it fits.
> If it doesn't, I put it on a line by itself, so it doesn't get lost.
> It's probably not entirely consistent, but it works well for me.
> 
> Note that I also dropped some extraneous parentheses.  Too many
> parentheses can be as confusing as too few, and I think it's
> sufficiently obvious that "==" and "!=" bind more tightly than "&&".
> The alignment of the subexpressions helps.
> 
> I do not suggest that my style is the only correct one.
> 

Yes, you missed the point. I prefer this way :

if ( NULL != pointer1 &&
      0x152 == pointer1->field7 )
  {
      return;
  }

Can save you some debugging time :)
0
Reply vladaspams2 (160) 3/4/2010 2:02:56 PM

Vladimir Jovic <vladaspams@gmail.com> writes:

>Yes, you missed the point. I prefer this way :

>if ( NULL != pointer1 &&
>      0x152 == pointer1->field7 )
>  {
>      return;
>  }

>Can save you some debugging time :)

But it makes the code much more difficult to read.

You're not testing that NULL now has a different value or that
0x152 has a different value.


Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/4/2010 2:25:18 PM

Vladimir Jovic <vladaspams@gmail.com> writes:

>
> Yes, you missed the point. I prefer this way :
>
> if ( NULL != pointer1 &&
>       0x152 == pointer1->field7 )
>   {
>       return;
>   }
>
> Can save you some debugging time :)
>

I congratulate you : it has everything that sucks in pseudo styling.

1) unnecessary waste of vertical screen usage
2) horrible "Non english" comparisons.

When discussing vars in computing it is normal to discuss the variables
b name.

You dont say "if pi is larger than p".You say "if p is larger than
pi". You're style is nothing more than fancy for fancy's sake IMO.

> if (pointer1 && pointer1->field7==0x152)
>   return;

Is less code and more readable and doesnt use any clever clogs
reversals.


-- 
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c
0
Reply rgrdev_ (1087) 3/4/2010 2:40:52 PM

In <oct467-nu6.ln1@news.eternal-september.org> Richard <rgrdev_@gmail.com> writes:

> When discussing vars in computing it is normal to discuss the variables
> b name.

> You dont say "if pi is larger than p".You say "if p is larger than
> pi". You're style is nothing more than fancy for fancy's sake IMO.

No, it does actually do something: it will throw a compile error if you
mistype == as =.

To demonstrate, imagine that you intended to type this:

  if (x == 7)

But you mistakenly typed this:

  if (x = 7)

This is legal code but will not behave in the way you intended.

But if you had typed it this way:

  if (7 = x)

The compiler will throw an error.

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

0
Reply gordon16 (617) 3/4/2010 3:52:18 PM

John Gordon  wrote in message <hmokvi$53g$1@reader1.panix.com>:
> No, it does actually do something: it will throw a compile error if you
> mistype == as =.

Any half-decent compiler can throw a warning for that.
0
Reply george54 (194) 3/4/2010 3:53:09 PM

John Gordon <gordon@panix.com> writes:

>To demonstrate, imagine that you intended to type this:

>  if (x == 7)

>But you mistakenly typed this:

>  if (x = 7)

>This is legal code but will not behave in the way you intended.

>But if you had typed it this way:

>  if (7 = x)

>The compiler will throw an error.

But leaves you with unreadable code.

You are using the wrong tools; proper tools will detect this.

lint:

(4) warning: assignment operator "=" found where "==" was expected

and gcc:

foo.c:4: warning: suggest parentheses around assignment used as truth value


Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/4/2010 4:06:09 PM

On Mar 4, 10:52=A0am, John Gordon <gor...@panix.com> wrote:
> In <oct467-nu6....@news.eternal-september.org> Richard <rgrd...@gmail.com=
> writes:
>
> > When discussing vars in computing it is normal to discuss the variables
> > b name.
> > You dont say "if pi is larger than p".You say "if p is larger than
> > pi". You're style is nothing more than fancy for fancy's sake IMO.
>
> No, it does actually do something: it will throw a compile error if you
> mistype =3D=3D as =3D.
>
> To demonstrate, imagine that you intended to type this:
>
> =A0 if (x =3D=3D 7)
>
> But you mistakenly typed this:
>
> =A0 if (x =3D 7)
>
> This is legal code but will not behave in the way you intended.
>
> But if you had typed it this way:
>
> =A0 if (7 =3D x)
>
> The compiler will throw an error.

I prefer readability over a marginal technique to reduce bugs.
English is meant to be read left to right, and is how I prefer to read
code, not the Yoda style '7 =3D=3D x'.  If the potential bug really causes
you grief, maybe pass a flag that makes the compiler flag 'x =3D 7' as
warnings?

> --
> John Gordon =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 A is for Amy, who fell do=
wn the stairs
> gor...@panix.com =A0 =A0 =A0 =A0 =A0 =A0 =A0B is for Basil, assaulted by =
bears
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 -- Edward=
 Gorey, "The Gashlycrumb Tinies"

0
Reply jadill33 (201) 3/4/2010 4:11:02 PM

Vladimir Jovic <vladaspams@gmail.com> writes:
> Keith Thompson wrote:
>> Vladimir Jovic <vladaspams@gmail.com> writes:
>>> Scott Lurndal wrote:
>>>>   I personally place the condition operator at the front, as
>>>>   William does, but nested.
>>>>
>>>>    if ((pointer1 != NULL)
>>>>     && (pointer1->field7 == 0x152)) {
>>>>        return;
>>>>    }
>>> if ( ( pointer1 =! NULL )
>>>      && ( pointer1->field7 = 0x152 ) ) {
>>>         return;
>>>     }
>>>
>>> ops && ops
>>
>> if ( pointer1 != NULL &&
>>      pointer1->field7 == 0x152 )
>> {
>>     return;
>> }
>>
[...]
>
> Yes, you missed the point. I prefer this way :
>
> if ( NULL != pointer1 &&
>      0x152 == pointer1->field7 )
>  {
>      return;
>  }
>
> Can save you some debugging time :)

Oh, I see.  I noticed the use of "=!" for "!=" and "=" for "==", but
assumed there were unintentional typos.

``pointer1 =! NULL'', of course, parses as ``pointer1 = !NULL''.
``!NULL'' evaluates to 1, and assigning an int value (other than a
null pointer constant) to a pointer object requires a diagnostic.

But yes, I'm familiar with the convention of putting the constant
expression on the left hand side of a comparison operator, and with
all the arguments in favor of it.  Personally, I find it ugly.
No offense.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/4/2010 4:20:51 PM

Keith Thompson <kst-u@mib.org> writes:

>``pointer1 =! NULL'', of course, parses as ``pointer1 = !NULL''.
>``!NULL'' evaluates to 1, and assigning an int value (other than a
>null pointer constant) to a pointer object requires a diagnostic.

And for other types the compiler or lint will also create a
diagnostic.

(4) warning: assignment operator "=" found where "==" was expected
(4) warning: constant operand to op: "!"

>But yes, I'm familiar with the convention of putting the constant
>expression on the left hand side of a comparison operator, and with
>all the arguments in favor of it.  Personally, I find it ugly.
>No offense.

Same here.

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/4/2010 4:27:26 PM

John Gordon <gordon@panix.com> writes:
> In <oct467-nu6.ln1@news.eternal-september.org> Richard <rgrdev_@gmail.com> writes:
>> When discussing vars in computing it is normal to discuss the variables
>> b name.
>
>> You dont say "if pi is larger than p".You say "if p is larger than
>> pi". You're style is nothing more than fancy for fancy's sake IMO.
>
> No, it does actually do something: it will throw a compile error if you
> mistype == as =.
>
> To demonstrate, imagine that you intended to type this:
>
>   if (x == 7)
>
> But you mistakenly typed this:
>
>   if (x = 7)
>
> This is legal code but will not behave in the way you intended.

It is a bad idea to try to solve social problems with technical
means. The problem behind this is that = in C is a so-called 'false
cognate' for people who are intimately familiar with mathematics, that
is, a term in a foreign language which 'looks' very similar to a
loosely related term in one's mother tongue, but with a (subtly)
different meaning. This means that such people will likely confuse =
and == in C intuitively and have a hard time spotting such an error
since the text 'looks right' according to the set of conventions they
are so used to that they no longer actively think about them.

But this really only means that average people well-versed in
mathematics shouldn't attempt to code in C because they will likely
make basic errors other people wouldn't.
0
Reply rweikusat (2679) 3/4/2010 4:29:43 PM

John Gordon <gordon@panix.com> writes:

> In <oct467-nu6.ln1@news.eternal-september.org> Richard <rgrdev_@gmail.com> writes:
>
>> When discussing vars in computing it is normal to discuss the variables
>> b name.
>
>> You dont say "if pi is larger than p".You say "if p is larger than
>> pi". You're style is nothing more than fancy for fancy's sake IMO.
>
> No, it does actually do something: it will throw a compile error if you
> mistype == as =.

I know. I program C.

Its a silly little style. Sorry.

The same "error" can happen if "p=q()".

The ugliness and "non naturalness" as well as the inconsistency it
brings in outweigh any advantage.
0
Reply rgrdev_ (1087) 3/4/2010 5:16:02 PM

On 2010-03-04, John Gordon <gordon@panix.com> wrote:
> No, it does actually do something: it will throw a compile error if you
> mistype == as =.

But gcc gives a warning for it, anyway.  And "x == 7" is much more readable
than "7 == x".

At least, for English speakers it is.  I don't know; maybe there are languages
in which saying "if x is equal to y" implies that x is the constant and y
is the variable.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/4/2010 5:28:14 PM

On 2010-03-04, Nicolas George <nicolas$george@salle-s.org> wrote:
> John Gordon  wrote in message <hmokvi$53g$1@reader1.panix.com>:
>> No, it does actually do something: it will throw a compile error if you
>> mistype == as =.
>
> Any half-decent compiler can throw a warning for that.

But warnings can be missed, ignored, etc., while the
compilation error must be attended to (to succesfully
compile, at least).
0
Reply egportal2002 (6) 3/4/2010 5:38:06 PM

Edgardo Portal  wrote in message
<hmor5u$8r2$1@news.eternal-september.org>:
> But warnings can be missed, ignored, etc., while the
> compilation error must be attended to (to succesfully
> compile, at least).

And people can also purposefully edit the source to add bugs.

If the programmer is trying to make a good, working program, it enables most
warnings and tries to correct them all.
0
Reply george54 (194) 3/4/2010 5:47:18 PM

Edgardo Portal <egportal2002@yahoo.com> writes:
> On 2010-03-04, Nicolas George <nicolas$george@salle-s.org> wrote:
>> John Gordon  wrote in message <hmokvi$53g$1@reader1.panix.com>:
>>> No, it does actually do something: it will throw a compile error if you
>>> mistype == as =.
>>
>> Any half-decent compiler can throw a warning for that.
>
> But warnings can be missed, ignored, etc., while the
> compilation error must be attended to (to succesfully
> compile, at least).

Social problem #2: People who desire to avoid any work they can expect
to be able to avoid now with reasonable safety will make a bad job of
everything.
0
Reply rweikusat (2679) 3/4/2010 6:17:06 PM

Edgardo Portal <egportal2002@yahoo.com> writes:
>On 2010-03-04, Nicolas George <nicolas$george@salle-s.org> wrote:
>> John Gordon  wrote in message <hmokvi$53g$1@reader1.panix.com>:
>>> No, it does actually do something: it will throw a compile error if you
>>> mistype == as =.
>>
>> Any half-decent compiler can throw a warning for that.
>
>But warnings can be missed, ignored, etc., while the
>compilation error must be attended to (to succesfully
>compile, at least).

gcc has -Wall and -Werror.   Both are recommended.

Production code should never have compilation warnings.

scott
0
Reply scott 3/4/2010 6:22:57 PM

On 3/4/2010 12:47 PM, Nicolas George wrote:
> Edgardo Portal  wrote in message
> <hmor5u$8r2$1@news.eternal-september.org>:
>> But warnings can be missed, ignored, etc., while the
>> compilation error must be attended to (to succesfully
>> compile, at least).
>
> And people can also purposefully edit the source to add bugs.
>
> If the programmer is trying to make a good, working program, it enables most
> warnings and tries to correct them all.

This isn't always feasible, especially when the code throwing the
warnings doesn't belong to you.  On the project I currently work for
it invariably occurs that when I compile a package I end up getting
hundreds of warnings from the various packages it depends on.
Sifting through all those warnings looking for one that might have been
added by the code I modified is simply infeasible.  An error, on the 
other hand, stands out much better, and must be fixed for the code to
compile.

--
Dan Giaimo
0
Reply dgiaimo (34) 3/4/2010 6:27:55 PM

On 2010-03-04, Scott Lurndal <scott@slp53.sl.home> wrote:
> Edgardo Portal <egportal2002@yahoo.com> writes:
>>On 2010-03-04, Nicolas George <nicolas$george@salle-s.org> wrote:
>>> John Gordon  wrote in message <hmokvi$53g$1@reader1.panix.com>:
>>>> No, it does actually do something: it will throw a compile error if you
>>>> mistype == as =.
>>>
>>> Any half-decent compiler can throw a warning for that.
>>
>>But warnings can be missed, ignored, etc., while the
>>compilation error must be attended to (to succesfully
>>compile, at least).
>
> gcc has -Wall and -Werror.   Both are recommended.
>
> Production code should never have compilation warnings.
>
> scott

That can be hard to adhere to in practice, particularly if
you're using a lot of 3rd-party code.
0
Reply egportal2002 (6) 3/4/2010 7:04:00 PM

"news.telesweet.net" <dgiaimo@gmail.com> writes:

>This isn't always feasible, especially when the code throwing the
>warnings doesn't belong to you.  On the project I currently work for
>it invariably occurs that when I compile a package I end up getting
>hundreds of warnings from the various packages it depends on.
>Sifting through all those warnings looking for one that might have been
>added by the code I modified is simply infeasible.  An error, on the 
>other hand, stands out much better, and must be fixed for the code to
>compile.

And then there's "diff"; if you compile your own code (new code should
add warnings) and other code, then it should be possible to filter out
the "new" warnings.  It is part of our standard practice.

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/4/2010 7:33:16 PM

>
>
> But this really only means that average people well-versed in 
> mathematics shouldn't attempt to code in C because they will likely 
> make basic errors other people wouldn't.
>
I'm sure that they'll be delighted to hear that it's their fault for 
being mathematicians, and not the C language's fault.

0
Reply J.deBoynePollard-newsgroups (95) 3/4/2010 8:32:08 PM

On 04/03/10 18:22, Scott Lurndal wrote:
[...]
> gcc has -Wall and -Werror.   Both are recommended.

But for gods' sake remember to turn -Werror off before shipping your
code. (-Werror causes any warnings to error out.)

gcc has -Werror turned on in distributions. Unfortunately as later
versions of gcc produce more warnings, you now have a situation where
trying to build gcc with gcc can fail if the host compiler is different
from the one the gcc authors were using.

....

Incidentally, the Unix I'm working on right now has the following code
in one of the system header files:

#define prfillset(x) {int __t; \
                     for (__t=0;__t<sizeof(*(x))/sizeof(ulong);__t++) \
                     ((ulong *)(x))[__t]=-1; }

Yes, __t is an int, it's being compared against sizeof() which returns
an unsigned int, which means that every invocation of prfillset()
produces a compile-time warning. -Werror is not useful on this platform.

-- 
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ 𝕻𝖍'𝖓𝖌𝖑𝖚𝖎 𝖒𝖌𝖑𝖜'𝖓𝖆𝖋𝖍 𝕮𝖙𝖍𝖚𝖑𝖍𝖚
│ 𝕽'𝖑𝖞𝖊𝖍 𝖜𝖌𝖆𝖍'𝖓𝖆𝖌𝖑 𝖋𝖍𝖙𝖆𝖌𝖓.
0
Reply dg (324) 3/4/2010 8:34:42 PM

>
>
> English is meant to be read left to right, and is how I prefer to read 
> code, not the Yoda style '7 == x'.
>
Then the C and C++ declaration syntaxes, which are read spiral-fashion 
(per David Anderson, 1994-05-06), are not for you, grasshopper.

0
Reply J.deBoynePollard-newsgroups (95) 3/4/2010 8:35:46 PM

>
>
> And "x == 7" is much more readable than "7 == x".
>
> At least, for English speakers it is. I don't know; maybe there are 
> languages in which saying "if x is equal to y" implies that x is the 
> constant and y is the variable.
>
Nonsense.  This is nothing to do with speaking English.  There are 
plenty of examples of English prose that use that ordering, from the 
King James Bible through handbooks on baseball to Richard Dawkins.  You 
only find the ordering natural in C for purely circular reasons:  It's 
natural to (most) C programmers because that's how most C language code 
that they have read is written.  (And it's written that way because 
"It's natural.")  Nothing more, and nothing as a result of the English 
language.

0
Reply J.deBoynePollard-newsgroups (95) 3/4/2010 8:35:49 PM

On Mar 4, 3:32=A0pm, Jonathan de Boyne Pollard <J.deBoynePollard-
newsgro...@NTLWorld.COM> wrote:
> > But this really only means that average people well-versed in
> > mathematics shouldn't attempt to code in C because they will likely
> > make basic errors other people wouldn't.
>
> I'm sure that they'll be delighted to hear that it's their fault for
> being mathematicians, and not the C language's fault.

We mathematicians claim as a birth right
to make the same basic errors in all
programming languages!

--c
0
Reply hardmath (76) 3/4/2010 9:33:15 PM

On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>
>>
>> And "x == 7" is much more readable than "7 == x".
>>
>> At least, for English speakers it is. I don't know; maybe there are
>> languages in which saying "if x is equal to y" implies that x is the
>> constant and y is the variable.
>>
> Nonsense. This is nothing to do with speaking English. There are plenty
> of examples of English prose that use that ordering, from the King James
> Bible through handbooks on baseball to Richard Dawkins. You only find
> the ordering natural in C for purely circular reasons: It's natural to
> (most) C programmers because that's how most C language code that they
> have read is written. (And it's written that way because "It's
> natural.") Nothing more, and nothing as a result of the English language.

Rubbish. You don't say "if that chicken is an animal then I'll eat it", 
you say "If that animal is a chicken then I'll eat it".

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/4/2010 10:28:56 PM

Tim Streater <timstreater@waitrose.com> writes:

> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>>
>>>
>>> And "x == 7" is much more readable than "7 == x".
>>>
>>> At least, for English speakers it is. I don't know; maybe there are
>>> languages in which saying "if x is equal to y" implies that x is the
>>> constant and y is the variable.
>>>
>> Nonsense. This is nothing to do with speaking English. There are plenty
>> of examples of English prose that use that ordering, from the King James
>> Bible through handbooks on baseball to Richard Dawkins. You only find
>> the ordering natural in C for purely circular reasons: It's natural to
>> (most) C programmers because that's how most C language code that they
>> have read is written. (And it's written that way because "It's
>> natural.") Nothing more, and nothing as a result of the English language.
>
> Rubbish. You don't say "if that chicken is an animal then I'll eat
> it", you say "If that animal is a chicken then I'll eat it".

If wrong you are, my hat I will eat.
-- 
Online waterways route planner            | http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
0
Reply 3-nospam (285) 3/4/2010 10:39:57 PM

In comp.unix.programmer Nick <3-nospam@temporary-address.org.uk> wrote:
> If wrong you are, my hat I will eat.

Yes, Master Yoda :)

rick jones
-- 
a wide gulf separates "what if" from "if only"
these opinions are mine, all mine; HP might not want them anyway... :)
feel free to post, OR email to rick.jones2 in hp.com but NOT BOTH...
0
Reply rick.jones2 (1061) 3/4/2010 10:44:24 PM

In article <4b8fc2ce$0$22943$e4fe514c@news.xs4all.nl>,
Casper H.S. Dik  <Casper.Dik@Sun.COM> wrote:
>Vladimir Jovic <vladaspams@gmail.com> writes:
>
>>Yes, you missed the point. I prefer this way :
>
>>if ( NULL != pointer1 &&
>>      0x152 == pointer1->field7 )
>>  {
>>      return;
>>  }
>
>But it makes the code much more difficult to read.
>
>You're not testing that NULL now has a different value or that
>0x152 has a different value.

The != operator is symmetric, ``NULL != pointer'' and ``pointer != NULL''
mean exactly the same thing, and both expressions are easy to read.

You are not testing if the left operand now has a different value,
you are testing if the left and the right operand have different values.
0
Reply ike5 (222) 3/4/2010 10:54:31 PM

In article <oct467-nu6.ln1@news.eternal-september.org>,
Richard  <rgrdev_@gmail.com> wrote:
>>
>> Yes, you missed the point. I prefer this way :
>>
>> if ( NULL != pointer1 &&
>>       0x152 == pointer1->field7 )
>>   {
>>       return;
>>   }
>>
>> Can save you some debugging time :)
>
>I congratulate you : it has everything that sucks in pseudo styling.
>
>1) unnecessary waste of vertical screen usage

Who cares; use your scroll button.

>2) horrible "Non english" comparisons.

It's also "non chinese" and "non swahili". It's C, and in C the order
of the operands of the == and != operators is irrelevant.
You don't read arithmetic expressions like you read a work of literature.

>When discussing vars in computing it is normal to discuss the variables
>b name.
>
>You dont say "if pi is larger than p".You say "if p is larger than
>pi". 

No. The two statements do not have the same meaning.
I think you mean "if pi is larger than p" vs. "if p is less than pi".
If you have trouble understanding ``pi > p'' then perhaps you shouldn't
be programming.

>You're style is nothing more than fancy for fancy's sake IMO.

Of course; so is your style (and so is mine).
0
Reply ike5 (222) 3/4/2010 11:08:59 PM

On 04/03/2010 22:39, Nick wrote:
> Tim Streater<timstreater@waitrose.com>  writes:
>
>> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>>>
>>>>
>>>> And "x == 7" is much more readable than "7 == x".
>>>>
>>>> At least, for English speakers it is. I don't know; maybe there are
>>>> languages in which saying "if x is equal to y" implies that x is the
>>>> constant and y is the variable.
>>>>
>>> Nonsense. This is nothing to do with speaking English. There are plenty
>>> of examples of English prose that use that ordering, from the King James
>>> Bible through handbooks on baseball to Richard Dawkins. You only find
>>> the ordering natural in C for purely circular reasons: It's natural to
>>> (most) C programmers because that's how most C language code that they
>>> have read is written. (And it's written that way because "It's
>>> natural.") Nothing more, and nothing as a result of the English language.
>>
>> Rubbish. You don't say "if that chicken is an animal then I'll eat
>> it", you say "If that animal is a chicken then I'll eat it".
>
> If wrong you are, my hat I will eat.

My case I rest.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/4/2010 11:15:25 PM

In article <87vddcdp8o.fsf@fever.mssgmbh.com>,
Rainer Weikusat  <rweikusat@mssgmbh.com> wrote:
>John Gordon <gordon@panix.com> writes:
>It is a bad idea to try to solve social problems with technical
>means. The problem behind this is that = in C is a so-called 'false
>cognate' for people who are intimately familiar with mathematics, that
>is, a term in a foreign language which 'looks' very similar to a
>loosely related term in one's mother tongue, but with a (subtly)
>different meaning. This means that such people will likely confuse =
>and == in C intuitively and have a hard time spotting such an error
>since the text 'looks right' according to the set of conventions they
>are so used to that they no longer actively think about them.
>
>But this really only means that average people well-versed in
>mathematics shouldn't attempt to code in C because they will likely
>make basic errors other people wouldn't.

Using ``='' for something other than equality was, in my opinion, the
most unfortunate design decision in the design of C.

We should be glad that the language designers left it at that, and did not
use ``+'' for ``or'', and ``++'' for addition  ;-)
0
Reply ike5 (222) 3/4/2010 11:20:37 PM

On 4 Mar, 22:44, Rick Jones <rick.jon...@hp.com> wrote:
> In comp.unix.programmer Nick <3-nos...@temporary-address.org.uk> wrote:
>
> > If wrong you are, my hat I will eat.

Or, more Yoda-esque: If wrong you are, eat my hat I will.

> Yes, Master Yoda :)

Reminds me of a phrase from, I think, Watership Down (the book, not
the animation): It's lost you are is it? Where was that from? Not the
far reaches of the Empire but deepest Wales. Maybe the force is strong
there also....

James
0
Reply james.harris.1 (384) 3/4/2010 11:47:49 PM

Ian Collins <ian-news@hotmail.com> writes:

> Tim Rentsch wrote:
>> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>
>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>
>>>> Anand Hariharan wrote:
>>>> <snip>
>>>>
>>>>> Haven't seen anyone point this out:
>>>>>
>>>>> Rather than -
>>>>>
>>>>>   #define MAXNUMFILES 1024
>>>>>
>>>>> - prefer -
>>>>>
>>>>>   const int MaxNumFiles = 1024;
>>>>>
>>>>>
>>>>> That way your preprocessor won't do as much damage.
>>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>>> an array size.
>>> It's a problem in C99 too, if the array is defined at file scope or it
>>> has internal linkage.  There are other reasons why it's not a great
>>> idea in C99.  They stem from the fact that MaxNumFiles is not
>>> permitted as part of a constant expression.  [snip elaboration]
>>
>> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
>> expression, albeit an implementation-specific constant expression;
>> it just isn't _required_ to be a portable constant expression.
>
> What?  You could say just about any nonsense is permitted as part of
> an implementation-specific expression.
>
> That doesn't alter that fact that in C90 or C99, MaxNumFiles is not
> permitted as part of a constant expression.

Yes, such things are explicitly allowed as implementation-specific
forms of constant expressions, in both C90 (s 6.4) and C99 (6.6p10).
0
Reply txr2511 (42) 3/4/2010 11:54:40 PM

On 2010-03-04, Chip Eastham <hardmath@gmail.com> wrote:
> We mathematicians claim as a birth right
> to make the same basic errors in all
> programming languages!

I'm not sure which ending fits better:

.... bringing a whole new meaning to the phrase "without loss of generality".
.... thus reducing everything to a class of problems already solved.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/4/2010 11:59:37 PM

On 2010-03-04, Ike Naar <ike@localhost.claranet.nl> wrote:
> It's also "non chinese" and "non swahili". It's C, and in C the order
> of the operands of the == and != operators is irrelevant.

To the compiler, yes.  To the reader, no.

> You don't read arithmetic expressions like you read a work of literature.

You sort of do, actually.

In general, while everyone knows that addition is commutative, people will
tend (slightly) to see "x + 3" as "basically x, but with 3 more", and "3 + x"
as "basically 3, but with x more".  The lefthand operand has primacy, and
this *does* matter.

It's the same reason that:
	the man was eaten by the bear
and
	the bear ate the man
are not the same statement, even though they have the same information
in them if you ignore connotations.  One is telling you about the bear's
diet; one is telling you about what happened to a man.

So even if it's the same for the compiler, if you write:
	if (x != y)
the reader assumes that x is the value which is in question, not y.  Maybe
the reader is wrong, but the assumption is sufficiently deeply wired in
most brains that there is no point trying to outsmart the reader.  The reader
will pick up the connotation with very high reliability, *even if it's wrong*.
Thus, your best bet when writing code so that humans can read it reliably
remains to honor the convention even though there's no reason in C itself to
do so.

It's like indentation.  We don't indent in C because the compiler cares, but
because it helps readers understand.  Bad indentation can result in readers
misunderstanding code, because they trust the indentation to be a cue.
Similarly, reversing the order of the comparands in an equality or inequality
comparison, even though in theory it changes nothing semantically, can cause
readers to misunderstand code.

I write for humans, not compilers.  Compilers aren't subject to assumptions,
or to difficulty keeping track of the code.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 12:05:02 AM

Tim Streater <timstreater@waitrose.com> writes:
> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>> And "x == 7" is much more readable than "7 == x".
>>>
>>> At least, for English speakers it is. I don't know; maybe there are
>>> languages in which saying "if x is equal to y" implies that x is the
>>> constant and y is the variable.
>>>
>> Nonsense. This is nothing to do with speaking English. There are plenty
>> of examples of English prose that use that ordering, from the King James
>> Bible through handbooks on baseball to Richard Dawkins. You only find
>> the ordering natural in C for purely circular reasons: It's natural to
>> (most) C programmers because that's how most C language code that they
>> have read is written. (And it's written that way because "It's
>> natural.") Nothing more, and nothing as a result of the English language.
>
> Rubbish. You don't say "if that chicken is an animal then I'll eat
> it", you say "If that animal is a chicken then I'll eat it".

The word "is" isn't an equality operator in that context; it's more
like a set membership operator.  In fact, I think that most uses of
"is" in English mean something other than equality.

I suggest that in cases where "is" is used to denote equality,
usage is more symmetric than you might think.  "My brother is Fred
Thompson" and "Fred Thompson is my brother" seem equally clear to me
(and equally false, since that's not my brother's name).

If that (a specific creature) animal (more specific information to
help identify the creature) is a chicken (is a member of the set
of chickens) then I'll eat it.  Swapping "chicken" and "animal"
changes the meaning of the sentence.  By contrast, "x == 7" and
"7 == x" have exactly the same meaning in C; the only question is
which one more clearly expresses that meaning.

As I've said, I agree that "x == 7" is clearer.  More precisely,
I can state authoritatively that it's clearer *to me*.  If others
state that both forms are equally clear *to them*, I have no reason
to doubt it.

And someone who finds "x == 7" and "7 == x" equally clear is probably
thinking about it more clearly than I'm able to, and possibly having
trouble figuring out what my problem is.  (I'm not entirely sure
about that myself.)

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 12:31:01 AM

In article <slrnhovrde.6eh.usenet-nospam@guild.seebs.net>, Seebs <usenet-nospam@seebs.net> writes:
> On 2010-03-04, John Gordon <gordon@panix.com> wrote:
>> No, it does actually do something: it will throw a compile error if you
>> mistype == as =.
> 
> But gcc gives a warning for it, anyway.  And "x == 7" is much more readable
> than "7 == x".
> 
> At least, for English speakers it is.  I don't know; maybe there are languages
> in which saying "if x is equal to y" implies that x is the constant and y
> is the variable.

I've found the following phrases in Wiktionary:

http://en.wiktionary.org/wiki/equal

"Two plus two equals four."
"A and B are equal"
"A is equal to B"
"A is equal with B"

In Hungarian, forms 1 and 3 don't exist, but forms 2 and 4 are used with
the exact same structure. And yet I don't have any difficulty writing

	7 == x

and thinking, "7 is equal with x". Equality is symmetric. It took some
self-education (let's not be inquisitive about the why), but it was so
effective that now I frown on

	x == 7


.... I updated the function below to its current form two days ago;
you'll love to hate it:


static void
bailout(void)
{
  sigset_t tmp_set;

  if (pthread_equal(pthread_self(), main_thread)) {
    if (0 != opathn) {
      (void)unlink(opathn);
    }

    if (0 == sigemptyset(&tmp_set) && 0 == sigaddset(&tmp_set, SIGPIPE)
        && 0 == sigaddset(&tmp_set, SIGXFSZ)) {
      (void)pthread_sigmask(SIG_UNBLOCK, &tmp_set, 0);
    }
  }
  else {
    if (0 == sigemptyset(&tmp_set) && 0 == sigpending(&tmp_set)) {
      int chk;

      chk = sigismember(&tmp_set, SIGPIPE);
      if (0 == chk || (1 == chk && 0 == kill(pid, SIGPIPE))) {
        chk = sigismember(&tmp_set, SIGXFSZ);
        if ((0 == chk || (1 == chk && 0 == kill(pid, SIGXFSZ)))
            && 0 == kill(pid, SIGUSR1)) {
          pthread_exit(0);
        }
      }
    }
  }

  _exit(EX_FAIL);
}


(If called from the main thread, it removes the output file, if any.
Then it tries to unblock any pending SIGPIPE or SIGXFSZ. If it succeeds
(it should) and there is in fact any such signal pending for the whole
process or specifically for the main thread, such that its action is not
SIG_IGN (but SIG_DFL), then the process dies with one of those signals.
If unblocking fails (for whatever reason -- it shouldn't), or no such
signal was pending, or all relevant actions were SIG_IGN (yes, a signal
may remain pending even though its action is SIG_IGN), then the process
exits with status 1. (Unless a sub-thread encounters an EPIPE/EFBIG and
raises a SIGPIPE or SIGXFSZ, see below, to the process level, just
between unblocking and exiting, which is fine.)

If called from any sub-thread, if any of the following fails, the entire
process is terminated with exit status 1 as a last resort. Each
sub-thread has SIGPIPE and SIGXFSZ blocked. If any such signal is
pending on the thread, the thread forwards it to the process level, so
that it will become deliverable to the main thread. If any such signal
is already pending on the whole process, then the thread regenerates it
for the whole process -- an idempotent operation. Then the thread wakes
the main thread -- which is waiting for asynchronously generated signals
anyway like SIGINT and SIGTERM -- with a SIGUSR1 error notification, and
finally, the sub-thread terminates.

sigismember() can theoretically return -1, that's why 1 == chk is
checked after 0 == chk proves false.

tmp_set must be emptied before it can be passed to sigpending().)

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 12:37:51 AM

ike@localhost.claranet.nl (Ike Naar) writes:
> In article <4b8fc2ce$0$22943$e4fe514c@news.xs4all.nl>,
> Casper H.S. Dik  <Casper.Dik@Sun.COM> wrote:
>>Vladimir Jovic <vladaspams@gmail.com> writes:
>>
>>>Yes, you missed the point. I prefer this way :
>>
>>>if ( NULL != pointer1 &&
>>>      0x152 == pointer1->field7 )
>>>  {
>>>      return;
>>>  }
>>
>>But it makes the code much more difficult to read.
>>
>>You're not testing that NULL now has a different value or that
>>0x152 has a different value.
>
> The != operator is symmetric, ``NULL != pointer'' and ``pointer != NULL''
> mean exactly the same thing, and both expressions are easy to read.

Yes, the != operator is symmetric.  Yes, the two expressions mean
exactly the same thing.  No, ``NULL != pointer'' *isn't* easy to
read *for a lot of people*.  When I see a constant on the LHS and a
variable on the RHS of an "==" or "!=" operator, I have to mentally
swap the operands to understand what it means.

If you find them equally easy to read, I envy you.  Seriously.
It probably means that you have a better intuitive understanding
than I do.

Consider that the following expressions all have the same meaning:

    pointer != NULL
    NULL != pointer
    !(pointer == NULL)
    !!pointer
    pointer == NULL ? 0 : 1
    pointer == NULL == '/'/'/'

Most sane people would prefer either of the first two forms to the
others, simply because they're more readable.  Please understand, or
at least accept accept, than many of us prefer the first form to the
second for exactly the same (probably not entirely rational) reason.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 12:42:26 AM

On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> I suggest that in cases where "is" is used to denote equality,
> usage is more symmetric than you might think.  "My brother is Fred
> Thompson" and "Fred Thompson is my brother" seem equally clear to me
> (and equally false, since that's not my brother's name).

They're both equally clear, but they are communicating different things.
One of them is telling us something we might not already know, about an
entity already known to be your brother.  The other is telling us something
we might not already know, about an entity already known to be Fred Thompson.

Similarly, there's a big difference between "the person who committed the
murder was the butler" and "the butler committed the murder".  The former
is giving you information about a murder you already know about, the other
is giving you information about a butler you already know about.

> And someone who finds "x == 7" and "7 == x" equally clear is probably
> thinking about it more clearly than I'm able to, and possibly having
> trouble figuring out what my problem is.  (I'm not entirely sure
> about that myself.)

See above.  We use sentence structure to communicate additional information
that is not purely a function of the semantics of the words used.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 12:54:03 AM

Tim Streater wrote:
> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>>
>>>
>>> And "x == 7" is much more readable than "7 == x".
>>>
>>> At least, for English speakers it is. I don't know; maybe there are
>>> languages in which saying "if x is equal to y" implies that x is the
>>> constant and y is the variable.
>>>
>> Nonsense. This is nothing to do with speaking English. There are plenty
>> of examples of English prose that use that ordering, from the King James
>> Bible through handbooks on baseball to Richard Dawkins. You only find
>> the ordering natural in C for purely circular reasons: It's natural to
>> (most) C programmers because that's how most C language code that they
>> have read is written. (And it's written that way because "It's
>> natural.") Nothing more, and nothing as a result of the English language.
> 
> Rubbish. You don't say "if that chicken is an animal then I'll eat it",
> you say "If that animal is a chicken then I'll eat it".
> 
That depends on what "is" is.

-- 
Peter Moylan, Newcastle, NSW, Australia.      http://www.pmoylan.org
For an e-mail address, see my web page.
0
Reply Peter 3/5/2010 12:57:47 AM

Seebs <usenet-nospam@seebs.net> writes:
> On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
>> I suggest that in cases where "is" is used to denote equality,
>> usage is more symmetric than you might think.  "My brother is Fred
>> Thompson" and "Fred Thompson is my brother" seem equally clear to me
>> (and equally false, since that's not my brother's name).
>
> They're both equally clear, but they are communicating different things.
> One of them is telling us something we might not already know, about an
> entity already known to be your brother.  The other is telling us something
> we might not already know, about an entity already known to be Fred Thompson.

And the first sentence is less valid if I have more than one brother.

Perhaps this is a better example: "The ratio of a circle's
circumference to its diameter is pi" vs. "pi is the ratio of a
circle's circumference to its diameter".  But even there, the second
sentence looks more like a definition of "pi" than the first one does.

[snip]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 1:03:36 AM

On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> Perhaps this is a better example: "The ratio of a circle's
> circumference to its diameter is pi" vs. "pi is the ratio of a
> circle's circumference to its diameter".  But even there, the second
> sentence looks more like a definition of "pi" than the first one does.

Right.  They're answers to different questions.  One answers "I have here a
circumference and a diameter; what is the relationship between them?"  The
other answers "I have this number, what does it mean?"

Similarly, there's a reason that tax forms (famed, of course, for their
excellent language, right?) say "If your income is over $N" rather than "if
$N is less than your income".  (Ignoring the precise equality case, because
that's another kind of complexity.)  Likewise, it's "you must be at least 48
inches tall to go on this ride", not "48 inches must be less than your
height for you to go on this ride".

Idiomatic writing matters in both English and C.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 1:13:01 AM

In article <lny6i7tx8t.fsf@nuthaus.mib.org>, Keith Thompson <kst-u@mib.org> writes:

>     pointer == NULL == '/'/'/'

Fascinating :)

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 1:22:21 AM

Nicolas George wrote:
> If the programmer is trying to make a good, working program, it enables most
> warnings and tries to correct them all.

Programmers are its?!  Now I'm sure there are some bosses who feel that way ...


0
Reply gldncagrls (469) 3/5/2010 1:58:10 AM

In comp.unix.programmer Ike Naar <ike@localhost.claranet.nl> wrote:
> In article <87vddcdp8o.fsf@fever.mssgmbh.com>,
> Rainer Weikusat  <rweikusat@mssgmbh.com> wrote:
> >John Gordon <gordon@panix.com> writes:
> >It is a bad idea to try to solve social problems with technical
> >means. The problem behind this is that = in C is a so-called 'false
> >cognate' for people who are intimately familiar with mathematics, that
> >is, a term in a foreign language which 'looks' very similar to a
> >loosely related term in one's mother tongue, but with a (subtly)
> >different meaning. This means that such people will likely confuse =
> >and == in C intuitively and have a hard time spotting such an error
> >since the text 'looks right' according to the set of conventions they
> >are so used to that they no longer actively think about them.
> >
> >But this really only means that average people well-versed in
> >mathematics shouldn't attempt to code in C because they will likely
> >make basic errors other people wouldn't.

> Using ``='' for something other than equality was, in my opinion, the
> most unfortunate design decision in the design of C.

But it does mean equality. In fact, it commands it.

0
Reply William 3/5/2010 4:53:35 AM

In article <slrnhp0j1q.eil.usenet-nospam@guild.seebs.net>,
Seebs  <usenet-nospam@seebs.net> wrote:
>On 2010-03-04, Ike Naar <ike@localhost.claranet.nl> wrote:
>> It's also "non chinese" and "non swahili". It's C, and in C the order
>> of the operands of the == and != operators is irrelevant.
>
>To the compiler, yes.  To the reader, no.

To the mathematically inclined reader, yes.

>> You don't read arithmetic expressions like you read a work of literature.
>
>You sort of do, actually.
>In general, while everyone knows that addition is commutative, people will
>tend (slightly) to see "x + 3" as "basically x, but with 3 more", and "3 + x"
>as "basically 3, but with x more".  The lefthand operand has primacy, and
>this *does* matter.

It doesn't matter, but anybody can fool themselves that it does.
And then Alice convinces herself that 3+x is ugly and unreadable,
Bob opts for x+3 being error-prone and unreadable, and now what
should Carol write?

> [snip]
>
>It's like indentation.  We don't indent in C because the compiler cares, but
>because it helps readers understand.  Bad indentation can result in readers
>misunderstanding code, because they trust the indentation to be a cue.

Fully agreed.
But there a several (conflicting) styles of indentation that are
considered 'good', and a programmer should be able to understand
code that uses a reasonable indentation style. It makes no sense
to convince oneself that a reasonable style is "unreadable" simply
because it's not one's preferred style.

>Similarly, reversing the order of the comparands in an equality or inequality
>comparison, even though in theory it changes nothing semantically, can cause
>readers to misunderstand code.
>I write for humans, not compilers.  Compilers aren't subject to assumptions,
>or to difficulty keeping track of the code.

Humans, you can't please them all ;-)
0
Reply ike5 (222) 3/5/2010 6:00:39 AM

Casper H.S. Dik wrote:
> Keith Thompson <kst-u@mib.org> writes:
> 
>> ``pointer1 =! NULL'', of course, parses as ``pointer1 = !NULL''.
>> ``!NULL'' evaluates to 1, and assigning an int value (other than a
>> null pointer constant) to a pointer object requires a diagnostic.
> 
> And for other types the compiler or lint will also create a
> diagnostic.
> 
> (4) warning: assignment operator "=" found where "==" was expected
> (4) warning: constant operand to op: "!"


Cool. I didn't know I would get a warning.
0
Reply vladaspams2 (160) 3/5/2010 6:33:06 AM

On 2010-03-05, Ike Naar <ike@localhost.claranet.nl> wrote:
> In article <slrnhp0j1q.eil.usenet-nospam@guild.seebs.net>,
> Seebs  <usenet-nospam@seebs.net> wrote:
>>On 2010-03-04, Ike Naar <ike@localhost.claranet.nl> wrote:
>>> It's also "non chinese" and "non swahili". It's C, and in C the order
>>> of the operands of the == and != operators is irrelevant.

>>To the compiler, yes.  To the reader, no.

> To the mathematically inclined reader, yes.

I disagree.  I was raised by mathematicians, but I view statements and
expressions as often being written to communicate additional meaning.

> It doesn't matter, but anybody can fool themselves that it does.

The existence of even a small set of people to whom it matters means
it matters, because code is written for programmers first, and compilers
second.

> Fully agreed.
> But there a several (conflicting) styles of indentation that are
> considered 'good', and a programmer should be able to understand
> code that uses a reasonable indentation style. It makes no sense
> to convince oneself that a reasonable style is "unreadable" simply
> because it's not one's preferred style.

"convince oneself" implies a volitional act taken contrary to evidence
or experience.  I don't think that's involved here.  I wouldn't quite
call it "unreadable", but it certainly reduces my chances of following
code correctly on the first try.  When I see "if (x != y)" in C, I
unconsciously perceive it to be the case that x could vary and y couldn't.

Consider:
	for (i = 0; i < 10; ++i)

Why do we write "i < 10" rather than "10 >= i"?  Because i's the one that
varies, so "i is less than ten" is more idiomatic than "ten is greater than
or equal to i".

Now consider:
	for (i = 0; i < max; ++i)

even though "max" may vary over time, the assumption is that, for this loop,
i changes and max doesn't.  If someone wrote this loop, then altered max
within the loop while modifying i to keep it constant, it would be completely
incoherent.

So, now...
	for (l = head; l != NULL; l = l->next)

Clearly, this follows the same idiom.  If we flip the components of the
middle expression, we've suddenly gone off the standard idiom for the
condition in a for loop, and the reader is justifiably surprised.

And if the for loop should have "l != NULL" rather than "NULL != l" (and
it should), then so should an if statement, for consistency.

The time when that technique caught something compilers wouldn't catch
is long gone.  I don't think it's needed anymore.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:37:06 AM

James Harris <james.harris.1@googlemail.com> writes:

> On 4 Mar, 22:44, Rick Jones <rick.jon...@hp.com> wrote:
>> In comp.unix.programmer Nick <3-nos...@temporary-address.org.uk> wrote:
>>
>> > If wrong you are, my hat I will eat.
>
> Or, more Yoda-esque: If wrong you are, eat my hat I will.

But actually, thinking about it later (sad that I am) to make the 7==a
analogy better it should be "If wrong are you".   
-- 
Online waterways route planner            | http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
0
Reply 3-nospam (285) 3/5/2010 7:03:51 AM

[Interesting bunch of crossposts!]

Keith Thompson wrote:
> Tim Streater <timstreater@waitrose.com> writes:
>> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>>> And "x == 7" is much more readable than "7 == x".
>>>>
>>>> At least, for English speakers it is. I don't know; maybe there are
>>>> languages in which saying "if x is equal to y" implies that x is the
>>>> constant and y is the variable.
>>>>
>>> Nonsense. This is nothing to do with speaking English.

Correct. C and English are different languages, with different purposes 
and different idioms.

>>> You only find
>>> the ordering natural in C for purely circular reasons: It's natural to
>>> (most) C programmers because that's how most C language code that they
>>> have read is written. (And it's written that way because "It's
>>> natural.") Nothing more, and nothing as a result of the English language.

Right.

>> Rubbish. You don't say "if that chicken is an animal then I'll eat
>> it", you say "If that animal is a chicken then I'll eat it".

Tim, those two sentences don't mean the same thing. We're discussing 
value equality, not (as Keith nicely puts it) set membership. Closer 
example: "if that chicken's name is Edwina, I'll eat it" vs "if Edwina 
is that chicken's name, I'll eat it".

> By contrast, "x == 7" and
> "7 == x" have exactly the same meaning in C; the only question is
> which one more clearly expresses that meaning.

No, that's not the only question. That's *one* of the questions. Other 
questions include "is there truly no semantic difference?" and "does the 
gain in error detection outweigh the perceived loss in readability, if 
any?" My answers would be "there is truly no semantic difference" (but 
the fact of asking the question made me think for a moment to confirm 
that I was right about the answer), and "there is no loss in readability 
and some gain in error detection, so yes" - but obviously YMMV.

> As I've said, I agree that "x == 7" is clearer.  More precisely,
> I can state authoritatively that it's clearer *to me*.  If others
> state that both forms are equally clear *to them*, I have no reason
> to doubt it.

In English, there is a distinction, albeit a subtle one, between "is 
Fred the man who shot my chicken?" and "is the man who shot my chicken 
Fred?" It's not a semantic distinction, however; rather, it's a 
distinction of tone. In C, however, I can see no distinction. The 
comparison-for-equality operator takes two operands. If they have the 
same value, the operator yields the value 1. Otherwise, it yields the 
value 0. The fact that one of them is on the right and the other on the 
left (or, if you prefer, the fact that one of them is on the left and 
the other on the right) is purely a consequence of the fact that C is 
(mostly) linear and static in structure.

If I could animate C source, I'd have the operands orbiting the == 
operator like little (okay, big) electrons. Position is of no 
consequence. But the operands of = would be fixed, because order matters 
for =.

> And someone who finds "x == 7" and "7 == x" equally clear is probably
> thinking about it more clearly than I'm able to, and possibly having
> trouble figuring out what my problem is.  (I'm not entirely sure
> about that myself.)

(a) no comment either way;
(b) yes;
(c) interesting. :-)

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 7:18:52 AM

William Ahern <william@wilbur.25thandClement.com> writes:
> In comp.unix.programmer Ike Naar <ike@localhost.claranet.nl> wrote:
[...]
>> Using ``='' for something other than equality was, in my opinion, the
>> most unfortunate design decision in the design of C.
>
> But it does mean equality. In fact, it commands it.

Not for volatile objects or NaNs.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 7:41:04 AM

Seebs wrote:

<snip>

> When I see "if (x != y)" in C, I
> unconsciously perceive it to be the case that x could vary and y couldn't.

Why?

> Consider:
> 	for (i = 0; i < 10; ++i)
> 
> Why do we write "i < 10" rather than "10 >= i"?

Good question.

> Because i's the one that
> varies, so "i is less than ten" is more idiomatic than "ten is greater than
> or equal to i".

Why?

> Now consider:
> 	for (i = 0; i < max; ++i)
> 
> even though "max" may vary over time, the assumption is that, for this loop,
> i changes and max doesn't.

Why?


> If someone wrote this loop, then altered max
> within the loop while modifying i to keep it constant, it would be completely
> incoherent.

Why? Consider: an ordinary reversal loop:

while(f < h)
{
   e = a[f];
   a[f++] = a[h];
   a[h--] = e;
}

Which is the constant now? Should it be f<h, or h>f? (Strictly, they're 
not equivalent, but in this case either will do.)

> So, now...
> 	for (l = head; l != NULL; l = l->next)
> 
> Clearly, this follows the same idiom.  If we flip the components of the
> middle expression, we've suddenly gone off the standard idiom

C&V please.

> for the condition in a for loop, and the reader is justifiably surprised.

Why?

> And if the for loop should have "l != NULL" rather than "NULL != l" (and
> it should), then so should an if statement, for consistency.

Emerson.

> The time when that technique caught something compilers wouldn't catch
> is long gone.  I don't think it's needed anymore.

You'd be amazed at the antiquity of some compilers. At one recent site, 
I was somewhat surprised to find an entire project team still using 
MSC5.00a (and they seemed perfectly contented, too).

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 7:49:36 AM

Keith Thompson <kst-u@mib.org> writes:
>>But it does mean equality. In fact, it commands it.
>Not for volatile objects or NaNs.

  Not even for some other usages:

#include <stdio.h>
#include <limits.h>

int main( void )
{ char c = INT_MAX;
  printf( "%d\n", c == INT_MAX ); }

  �=� is a write operation.

  ASCII 1963 had a left arrow symbol �<--� with code 101 1111.
  But this does not exist in ASCII 1968.

0
Reply ram (2825) 3/5/2010 8:13:38 AM

David Given <dg@cowlark.com> writes:

>On 04/03/10 18:22, Scott Lurndal wrote:
>[...]
>> gcc has -Wall and -Werror.   Both are recommended.

>But for gods' sake remember to turn -Werror off before shipping your
>code. (-Werror causes any warnings to error out.)

>gcc has -Werror turned on in distributions. Unfortunately as later
>versions of gcc produce more warnings, you now have a situation where
>trying to build gcc with gcc can fail if the host compiler is different
>from the one the gcc authors were using.

>...

>Incidentally, the Unix I'm working on right now has the following code
>in one of the system header files:

>#define prfillset(x) {int __t; \
>                     for (__t=0;__t<sizeof(*(x))/sizeof(ulong);__t++) \
>                     ((ulong *)(x))[__t]=-1; }

>Yes, __t is an int, it's being compared against sizeof() which returns
>an unsigned int, which means that every invocation of prfillset()
>produces a compile-time warning. -Werror is not useful on this platform.

I'm not sure why they aren't using:

	memset(x, ~0, sizeof (*x))

Are you talking about Solaris?

Casper
-- 
Expressed in this posting are my opinions.  They are in no way related
to opinions held by my employer, Sun Microsystems.
Statements on Sun products included here are not gospel and may
be fiction rather than truth.
0
Reply Casper.Dik (623) 3/5/2010 8:21:03 AM

Richard Heathfield wrote:
) In English, there is a distinction, albeit a subtle one, between "is 
) Fred the man who shot my chicken?" and "is the man who shot my chicken 
) Fred?" It's not a semantic distinction, however; rather, it's a 
) distinction of tone.

Disagree.  The semantic difference is that the first object is the item
that we're interested in, and the second is something we wish to know of
the first.

) In C, however, I can see no distinction.

In C, I see the very same distinction as I mentioned above.
(Okay, so I'm not sure it's a semantic difference, but it is a
 difference that carries over to C)


) If I could animate C source, I'd have the operands orbiting the == 
) operator like little (okay, big) electrons. Position is of no 
) consequence. But the operands of = would be fixed, because order matters 
) for =.

How about:  x <- 2  and  2 -> x  as assignment operators ?
Then they can orbit as well.

After all, the two operands can be evaluated in any order, it's just
that the operator takes two different arguments (an lvalue and a value).


SaSW, Willem
-- 
Disclaimer: I am in no way responsible for any of the statements
            made in the above text. For all I know I might be
            drugged or something..
            No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
0
Reply willem5 (70) 3/5/2010 8:32:27 AM

In article <slrnhp1a11.hqg.usenet-nospam@guild.seebs.net>,
Seebs  <usenet-nospam@seebs.net> wrote:
>I disagree.  I was raised by mathematicians, but I view statements and
>expressions as often being written to communicate additional meaning.

But you must be careful not to assign additional meaning if it was
unintended by the author.

Suppose I want to add a and b, where a and b can have any value.
I don't know (or care) which one of a and b is larger.
Still, when adding them together, I must make a (in this case, arbitrary)
choice between writing (a+b) or (b+a).
Suppose I choose (a+b).
If you read my code, it would be unfortunate if you would conclude, from the
bare fact that I wrote the addition as (a+b), that a is the larger of
the two.

>"convince oneself" implies a volitional act taken contrary to evidence
>or experience.  I don't think that's involved here.  I wouldn't quite
>call it "unreadable", but it certainly reduces my chances of following
>code correctly on the first try.  When I see "if (x != y)" in C, I
>unconsciously perceive it to be the case that x could vary and y couldn't.

But that perception could be misleading.
Consider a binary search: in this case, both operands can vary:

    left = lowerbound;
    right = upperbound;
    while (left < right)
    {
      inbetween = (left + right) / 2;
      if (some_condition)
        left = inbetween;
      else
        right = inbetween;
    }

>Consider:
>	for (i = 0; i < 10; ++i)
>
>Why do we write "i < 10" rather than "10 >= i"?  Because i's the one that
>varies, so "i is less than ten" is more idiomatic than "ten is greater than
>or equal to i".

Another reason might be that "i < 10" and "10 >= i" are not the same thing.
0
Reply ike5 (222) 3/5/2010 8:42:08 AM

On 2010-03-05, Richard Heathfield <rjh@see.sig.invalid> wrote:
> Seebs wrote:
>> When I see "if (x != y)" in C, I
>> unconsciously perceive it to be the case that x could vary and y couldn't.

> Why?

Because it's idiomatic, and most of the time, code follows that idiom.

>> Because i's the one that
>> varies, so "i is less than ten" is more idiomatic than "ten is greater than
>> or equal to i".

> Why?

Idioms don't have to have any reason other than "that's how it's been done
before".  It's a communications tool; given a general pattern that it's the
varying part on the left, and the invariant part on the right, that's what
I expect whenever I see a comparison operator.

>> Now consider:
>> 	for (i = 0; i < max; ++i)

>> even though "max" may vary over time, the assumption is that, for this loop,
>> i changes and max doesn't.

> Why?

Because that's how the majority of code has been written.  Why is that?  I
don't know.  It's probably some combination of the pronunciation ("while
i is less than max" is more idiomatic than "while max is greater than or
equal to i") and the first few C books using it.

>> If someone wrote this loop, then altered max
>> within the loop while modifying i to keep it constant, it would be completely
>> incoherent.

> Why? Consider: an ordinary reversal loop:

> while(f < h)
> {
>    e = a[f];
>    a[f++] = a[h];
>    a[h--] = e;
> }

> Which is the constant now? Should it be f<h, or h>f? (Strictly, they're 
> not equivalent, but in this case either will do.)

Indeed, in that case, either will do.

But in many cases, there's a clear preference, and even if you don't share
it, you will understand most code better and/or more quickly if you keep
that pattern in mind.

>> So, now...
>> 	for (l = head; l != NULL; l = l->next)

>> Clearly, this follows the same idiom.  If we flip the components of the
>> middle expression, we've suddenly gone off the standard idiom

> C&V please.

K&R.  I don't think you'll find a single test in there which goes the
other way.

>> for the condition in a for loop, and the reader is justifiably surprised.

> Why?

Again, it's an idiom.  It doesn't need a reason beyond the observation that
people tend to follow it.  There's no objective reason for most social
norms, or linguistic conventions, but once we have them, it's useful to
use them to communicate -- both to be aware that other people may be using
them, and to use them ourselves to make communication easier.

Even though it may not seem like much, in a complicated loop or set of
nested loops, having all the conditions follow a consistent idiom makes
it much easier to follow and comprehend code.  I'm not sure that which
idiom was picked would have mattered -- at this point, though, I've
seen thousands of loops with "p != NULL" as a condition, and extremely
few with "NULL != p", and similarly, thousands of "i < limit" and very
few "limit >= i", so when I see a condition, I read it that way first,
and only try something else if that works badly.

>90% of the time, the heuristic is right, so I stick with it, and I
encourage other people to use it, because it's a very valuable tool.

It's the same reason I advocate "char *x" rather than "char* x" or
"char * x" or "char\n*\nx" as a declaration -- it's a convention and it
seems to generally help me and other readers understand the code.  Maybe
it's not helpful for everyone, but I simply haven't seen it cause any
problems in living memory.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 8:45:44 AM

Vladimir Jovic <vladaspams@gmail.com> writes:
> Casper H.S. Dik wrote:
>> Keith Thompson <kst-u@mib.org> writes:
>>
>>> ``pointer1 =! NULL'', of course, parses as ``pointer1 = !NULL''.
>>> ``!NULL'' evaluates to 1, and assigning an int value (other than a
>>> null pointer constant) to a pointer object requires a diagnostic.
>>
>> And for other types the compiler or lint will also create a
>> diagnostic.
>>
>> (4) warning: assignment operator "=" found where "==" was expected
>> (4) warning: constant operand to op: "!"
>
> Cool. I didn't know I would get a warning.

It depends on the compiler and on how you invoke it.  The language
doesn't require warnings in these cases.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 9:02:34 AM

Ike Naar wrote in message <hmqg50$uf4$1@news.eternal-september.org>:
> If you read my code, it would be unfortunate if you would conclude, from the
> bare fact that I wrote the addition as (a+b), that a is the larger of
> the two.

It does not work that way. If you do not know anything about the variables,
then "x + q" and "q + x" will not mean anything to you.

On the other hand, if you know that x is the reference and q the cursor,
then the meaning of "q + x" will be more immediately obvious if it is
written "x + q". That is not a concious process, just a matter of mind
nimbleness.

Consider natural languages: some of them put the verb at the end of the
phrase (Latin, Japanese, German when it's a compound verb), but as far as I
know, most put the subject / theme of the phrase near the beginning.
Because, semantically and not grammatically, the subject / theme is the core
around which the complements, including the verb revolve.

>     while (left < right)

Why did you not write "while (right > left)"?

And why does everyone write "array[index]" instead of "index[array]"?
0
Reply george54 (194) 3/5/2010 9:49:00 AM

Nicolas George <nicolas$george@salle-s.org> writes:
>And why does everyone write "array[index]" instead of "index[array]"?

  Not everyone does so.

  �index[ array ]� actually is very natural as it is like what
  mathematicians call a �projection�, for example to get the
  coordinate  1 of the point x =( x�, x�, x� ), one uses the
  projection �p��, thus x� = p�( x ), where x� is the coordinate
  1 of x.

  �f( x )� can be written �p( x )( f )� as well, where p( x )
  is a �functional� assigning to every function f its value
  at the point x.

  Most people use �array[ index ]� just because they know more
  languages than just C, and most other languages only allow
  this.

0
Reply ram (2825) 3/5/2010 10:01:46 AM

Stefan Ram wrote in message
<index-20100305105826@ram.dialup.fu-berlin.de>:
>   �index[ array ]� actually is very natural

If it were natural, people would use it.

>						as it is like what
>   mathematicians call a �projection�, for example to get the
>   coordinate  1 of the point x =( x�, x�, x� ), one uses the
>   projection �p��, thus x� = p�( x ), where x� is the coordinate
>   1 of x.

It _does_ the same thing, but it does not _mean_ the same thing.
0
Reply george54 (194) 3/5/2010 10:22:08 AM

Willem wrote:
> Richard Heathfield wrote:
> ) In English, there is a distinction, albeit a subtle one, between "is 
> ) Fred the man who shot my chicken?" and "is the man who shot my chicken 
> ) Fred?" It's not a semantic distinction, however; rather, it's a 
> ) distinction of tone.
> 
> Disagree.  The semantic difference is that the first object is the item
> that we're interested in, and the second is something we wish to know of
> the first.

Not entirely convinced. In each case, we wish to know whether [Fred] and 
[the man who shot my chicken] are the same person.

> 
> ) In C, however, I can see no distinction.
> 
> In C, I see the very same distinction as I mentioned above.
> (Okay, so I'm not sure it's a semantic difference, but it is a
>  difference that carries over to C)

And I see much the same absence of distinction that I see in the English 
rendition.

> ) If I could animate C source, I'd have the operands orbiting the == 
> ) operator like little (okay, big) electrons. Position is of no 
> ) consequence. But the operands of = would be fixed, because order matters 
> ) for =.
> 
> How about:  x <- 2  and  2 -> x  as assignment operators ?
> Then they can orbit as well.

But then it wouldn't be C, would it?

> After all, the two operands can be evaluated in any order, it's just
> that the operator takes two different arguments (an lvalue and a value).

(Nit: operators take operands, not arguments.) The order of evaluation 
is not the issue here.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 10:32:07 AM

Seebs wrote:
> On 2010-03-05, Richard Heathfield <rjh@see.sig.invalid> wrote:
>> Seebs wrote:
>>> When I see "if (x != y)" in C, I
>>> unconsciously perceive it to be the case that x could vary and y couldn't.
> 
>> Why?
> 
> Because it's idiomatic, and most of the time, code follows that idiom.

I don't see how you get that y can't vary, just from seeing if(x != y). 
That's not an idiom - in fact, it's a ma short of idiomatic[1]. != takes 
two values; neither of them has to be a constant, and it's not terribly 
unusual to find that neither of them /is/ a constant.

> 
>>> Because i's the one that
>>> varies, so "i is less than ten" is more idiomatic than "ten is greater than
>>> or equal to i".
> 
>> Why?
> 
> Idioms don't have to have any reason other than "that's how it's been done
> before".

It's been done both ways before.

> It's a communications tool; given a general pattern that it's the
> varying part on the left, and the invariant part on the right, that's what
> I expect whenever I see a comparison operator.

Then, much of the time, you expect the wrong thing, since much of the 
time there is no invariant involved. If you were reading my code, you 
would very often find that, where an invariant /is/ involved in a 
comparison for equality, it's on the left. So your preconceptions would 
mislead you.

>>> Now consider:
>>> 	for (i = 0; i < max; ++i)
> 
>>> even though "max" may vary over time, the assumption is that, for this loop,
>>> i changes and max doesn't.
> 
>> Why?
> 
> Because that's how the majority of code has been written.

I am always suspicious of "we do it this way because most people do it 
this way". Sturgeon's Law and all that. I'm not saying we should do Y 
*because* most people do X; but following the crowd *just* for the sake 
of following the crowd is very often a bad idea, because the crowd is 
very often heading in the wrong direction.

<snip>

>>> If someone wrote this loop, then altered max
>>> within the loop while modifying i to keep it constant, it would be completely
>>> incoherent.
> 
>> Why? Consider: an ordinary reversal loop:
> 
>> while(f < h)
>> {
>>    e = a[f];
>>    a[f++] = a[h];
>>    a[h--] = e;
>> }
> 
>> Which is the constant now? Should it be f<h, or h>f? (Strictly, they're 
>> not equivalent, but in this case either will do.)
> 
> Indeed, in that case, either will do.

Sure. So which one is the constant you were expecting to see?

> But in many cases, there's a clear preference, and even if you don't share
> it, you will understand most code better and/or more quickly if you keep
> that pattern in mind.

I find it easier to keep in mind what the operators do with their operands.

<snip>

>>> [...] If we flip the components of the
>>> middle expression, we've suddenly gone off the standard idiom
> 
>> C&V please.
> 
> K&R.  I don't think you'll find a single test in there which goes the
> other way.

That's a rather weak basis for claiming a "standard idiom".

<snip>

[1] A bit OTT, but I couldn't resist using the idiom(!)

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 10:45:54 AM

On 4 Mar, 22:28, Tim Streater <timstrea...@waitrose.com> wrote:
> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>
>
>
> >> And "x == 7" is much more readable than "7 == x".
>
> >> At least, for English speakers it is. I don't know; maybe there are
> >> languages in which saying "if x is equal to y" implies that x is the
> >> constant and y is the variable.
>
> > Nonsense. This is nothing to do with speaking English. There are plenty
> > of examples of English prose that use that ordering, from the King James
> > Bible through handbooks on baseball to Richard Dawkins. You only find
> > the ordering natural in C for purely circular reasons: It's natural to
> > (most) C programmers because that's how most C language code that they
> > have read is written. (And it's written that way because "It's
> > natural.") Nothing more, and nothing as a result of the English language.
>
> Rubbish. You don't say "if that chicken is an animal then I'll eat it",
> you say "If that animal is a chicken then I'll eat it".

"is a" isn't the same as equality. It's more like "is a subset of"

0
Reply nick_keighley_nospam (4574) 3/5/2010 11:17:06 AM

ram@zedat.fu-berlin.de (Stefan Ram) writes:
> Keith Thompson <kst-u@mib.org> writes:
>>>But it does mean equality. In fact, it commands it.
>>Not for volatile objects or NaNs.
>
>   Not even for some other usages:
>
> #include <stdio.h>
> #include <limits.h>
>
> int main( void )
> { char c = INT_MAX;
>   printf( "%d\n", c == INT_MAX ); }
>
>   �=� is a write operation.

Of course it does. You are just playing games with automatic
conversions in the hope to confuse less knowledgable readers.
The line

	char c = INT_MAX

has implementation defined behaviour (although the gcc warning
'overflow in implicit constant conversion' suggests that the
people-with-an-axe-to-grind who already managed to convert their
pointless political statement about "proper integers" to code in
various other places are still seeking for a way around the
requirement to support the traditional, sane and useful behaviour
....). If the result is not that 'an implementation defined signal is
raised', an 'implementation defined automatic conversion' is supposed
to happen. Assuming that no such signal was raised and that
sizeof(int) > 1, INT_MAX cannot be converted to char without 'loss of
information'. The expression

	c == INT_MAX

causes the value stored in C to be converted back to int. Of course,
after

	char c = (char)INT_MAX

was performend,

	(int)c == INT_MAX

cannot be true if sizeof(int) > 1. The correct comparison would thus be

	c == (char)INT_MAX
0
Reply rweikusat (2679) 3/5/2010 12:24:05 PM

In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
Richard Heathfield <rjh@see.sig.invalid> writes:

> Seebs wrote:
> 
> <snip>
> 
>> When I see "if (x != y)" in C, I
>> unconsciously perceive it to be the case that x could vary and y couldn't.
> 
> Why?

Because he pronounces it as "x is not equal to y", and the subject of
that sentence is "x". "x" is the actor, the variable that is acting. "y"
is part of the prepositional phrase, it is static.

>> Consider:
>> 	for (i = 0; i < 10; ++i)
>> 
>> Why do we write "i < 10" rather than "10 >= i"?
> 
> Good question.

.... It's either me, or now two of you not noticing (or ignoring) that
"10 == i" satisfies the second but not the first.


>> Because i's the one that
>> varies, so "i is less than ten" is more idiomatic than "ten is greater than
>> or equal to i".
> 
> Why?

Because programmatically, "i" changes over time, 10 does not, and when
one reads out loud the controlling expression in English, the subject of
that sentence ("the actor") should be the entity that is acting.



> 
>> Now consider:
>> 	for (i = 0; i < max; ++i)
>> 
>> even though "max" may vary over time, the assumption is that, for this loop,
>> i changes and max doesn't.
> 
> Why?

Because when read out loud, "i" is the subject.


>> The time when that technique caught something compilers wouldn't catch
>> is long gone.  I don't think it's needed anymore.
> 
> You'd be amazed at the antiquity of some compilers. At one recent site, 
> I was somewhat surprised to find an entire project team still using 
> MSC5.00a (and they seemed perfectly contented, too).

The following version of gcc:

gcc (GCC) 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)

displays no warning for the following:

$ gcc -Wall -Wextra -ansi -pedantic -fsyntax-only try.c

----v----
static int
f(int a)
{
  return a = 3;
}

static int
g(int a)
{
  return (a = 3);
}
----^----

(Yes, we could fix that by taking "a" as const.)

Another example, showing that extra parentheses can shut up gcc:

----v----
int f(void);

static void
g(void)
{
  int a;

  a = f();
  if ((a = 2) || (a = 3)) {
    /* ... */
  }
}
----^----

This produces no warnings either. Although the parentheses are not
needed for the intended meaning, that is, for

	a == 2 || a == 3

some people might find the parenthesized version more readable, and when
they combine that with typing assignment instead of equality, then (this
version of) gcc won't warn them.

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 2:22:14 PM

ram@zedat.fu-berlin.de (Stefan Ram) writes:

> Nicolas George <nicolas$george@salle-s.org> writes:
>>And why does everyone write "array[index]" instead of "index[array]"?
>
>   Not everyone does so.

That is true of almost everything, no matter how reasonable the
behaviour in question is!

>   »index[ array ]« actually is very natural as it is like what
>   mathematicians call a »projection«, for example to get the
>   coordinate  1 of the point x =( x¹, x², x³ ), one uses the
>   projection »p¹«, thus x¹ = p¹( x ), where x¹ is the coordinate
>   1 of x.

This would be a stronger argument if the mathematicians did not put
the projection index after both the vector name and the letter
denoting the projection function.  That aside, the result looks like
1[x] but in fact it is not.  The notation the mathematicians end up
with is that of a function, and it is rare for p(x) to be equal to
x(p) in mathematics.

Yes, I really do get your point that 1[x] looks like the projection of
x, but my point is that when mathematicians want a notation for that
the result is something (a function application) that does not commute
like [] in C.  In other words, your example cuts both ways.

I don't think a mathematician, writing projections, would be any
happier with 1[x] than with x[1].

>   »f( x )« can be written »p( x )( f )« as well, where p( x )
>   is a »functional« assigning to every function f its value
>   at the point x.
>
>   Most people use »array[ index ]« just because they know more
>   languages than just C, and most other languages only allow
>   this.

Hmm...  I know more languages than just C; but I also know that, in C,
a[1] == 1[a] and yet I don't write the latter (except as an example of
the equivalence).  Am I just pandering to other people's ignorance?  I
don't think so.

How do you feel about i[array][j] and j[i[array]] (or, indeed,
j[array[i]] to get the full set)?

-- 
Ben.
0
Reply ben.usenet (6515) 3/5/2010 2:53:16 PM

Keith Thompson <kst-u@mib.org> writes:

> Ian Collins <ian-news@hotmail.com> writes:
>> Tim Rentsch wrote:
>>> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>>> Anand Hariharan wrote:
>>>>> <snip>
>>>>>> Haven't seen anyone point this out:
>>>>>>
>>>>>> Rather than -
>>>>>>
>>>>>>   #define MAXNUMFILES 1024
>>>>>>
>>>>>> - prefer -
>>>>>>
>>>>>>   const int MaxNumFiles = 1024;
>>>>>>
>>>>>>
>>>>>> That way your preprocessor won't do as much damage.
>>>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>>>> an array size.
>>>> It's a problem in C99 too, if the array is defined at file scope or it
>>>> has internal linkage.  There are other reasons why it's not a great
>>>> idea in C99.  They stem from the fact that MaxNumFiles is not
>>>> permitted as part of a constant expression.  [snip elaboration]
>>>
>>> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
>>> expression, albeit an implementation-specific constant expression;
>>> it just isn't _required_ to be a portable constant expression.
>>
>> What?  You could say just about any nonsense is permitted as part of
>> an implementation-specific expression.
>>
>> That doesn't alter that fact that in C90 or C99, MaxNumFiles is not
>> permitted as part of a constant expression.
>
> I think Tim is referring to C99 6.6p10:
>
>     An implementation may accept other forms of constant expressions.

Quite so.

> (I just noticed that this doesn't use the term
> "implementation-defined" implying, I think, that an implementation
> can accept other forms of constant expressions but isn't required
> to document them.)

My belief is that such forms of constant expressions still count
as language extensions.  If they are they must be documented,
because extensions are required to be documented.

> My understanding is that code that uses extensions in general (as
> permitted by C99 4p6) still require diagnostics if the code violates a
> constraint, but code that uses "other forms of constant expressions"
> does not.

Yes, diagnostics are still required for using any extensions that
is a syntax error or a constraint violation, but not not if they
don't, and that also includes "other forms of constant expressions".
(In other words my assessment here agrees with Keith's.)

> I'd say Tim's statement is correct, but I'd place the emphasis very
> differently: MaxNumFiles is not permitted as part of a constant
> expression (unless the implementation permits it under C99 6.6p10).

What I was trying to express is that this form of CE is allowed
in the sense of not being forbidden.  Some forms of CE are
"forbidden" in the sense that they would be constraint violations
even if they were language extensions, although of course they
could be accepted if a diagnostic were produced.  So in saying
MaxNumFiles is permitted as a CE, what I meant was it can be
accepted by an implementation without requiring any diagnostic
(with the additional qualifier, already explained, that there is
no portable requirement that it be accepted).

> Are there any real-world C implementations that take advantage of this
> permission?  Specifically, is there a C compiler that accepts
> additional forms of constant expressions in (what it claims to be)
> conforming mode?

Yes, I believe (some versions of?) gcc to be in this category.

> And why is that permission there in the first place?  What benefit
> does it really provide beyond the existing permission to provide
> extensions?

It seems clear that the point is to allow additional forms of
constant expression without absolutely insisting on generating a
diagnostic;  in other words to leave the question of diagnostics
up to the discretion of the implementation.  Without 6.6p10 any
other forms of constant expression wouldn't meet the Standard's
definition, and if used in places that need constant expressions
would cause constraint violations.
0
Reply txr2511 (42) 3/5/2010 2:59:49 PM

lacos@ludens.elte.hu (Ersek, Laszlo) writes:

> In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
> Richard Heathfield <rjh@see.sig.invalid> writes:
>
>> Seebs wrote:
<snip>
>>> Consider:
>>> 	for (i = 0; i < 10; ++i)
>>> 
>>> Why do we write "i < 10" rather than "10 >= i"?
>> 
>> Good question.
>
> ... It's either me, or now two of you not noticing (or ignoring) that
> "10 == i" satisfies the second but not the first.

I assumed that the "good question" reply was intended to draw Seebs's
attention to that fact; otherwise I'd have pointed it out.  Looking
at it now, with all of Richard's "why" questions, it seems possible
that the reply was not meant the way I assumed it was.

Either way, it's not really at the heart of the question unless you
think the switch *caused* the typo.

<snip>
-- 
Ben.
0
Reply ben.usenet (6515) 3/5/2010 3:13:03 PM

On Mar 4, 5:54=A0pm, Seebs <usenet-nos...@seebs.net> wrote:
> On 2010-03-05, Keith Thompson <ks...@mib.org> wrote:
>
> > I suggest that in cases where "is" is used to denote equality,
> > usage is more symmetric than you might think. =A0"My brother is Fred
> > Thompson" and "Fred Thompson is my brother" seem equally clear to me
> > (and equally false, since that's not my brother's name).
>
> They're both equally clear, but they are communicating different things.
> One of them is telling us something we might not already know, about an
> entity already known to be your brother. =A0The other is telling us somet=
hing
> we might not already know, about an entity already known to be Fred Thomp=
son.
>
> Similarly, there's a big difference between "the person who committed the
> murder was the butler" and "the butler committed the murder". =A0The form=
er
> is giving you information about a murder you already know about, the othe=
r
> is giving you information about a butler you already know about.
....

For those interested in what linguists have said about this, the terms
seem to be "topic" and "comment" or "theme" and "rheme".  In English,
the topic usually goes before the comment.  Of course even in a single
language the matter is complicated, and different linguists use
different approaches and different terminology.

--
Jerry Friedman
0
Reply jerry_friedman (6) 3/5/2010 3:26:43 PM

Ersek, Laszlo wrote:
> In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
> Richard Heathfield <rjh@see.sig.invalid> writes:
> 
>> Seebs wrote:
>>
>> <snip>
>>
>>> When I see "if (x != y)" in C, I
>>> unconsciously perceive it to be the case that x could vary and y couldn't.
>> Why?
> 
> Because he pronounces it as "x is not equal to y", and the subject of
> that sentence is "x". "x" is the actor, the variable that is acting. "y"
> is part of the prepositional phrase, it is static.

This is C we're discussing, not English. It is folly to pretend that the 
rules of English apply to C.

>>> Consider:
>>> 	for (i = 0; i < 10; ++i)
>>>
>>> Why do we write "i < 10" rather than "10 >= i"?
>> Good question.
> 
> .... It's either me, or now two of you not noticing (or ignoring) that
> "10 == i" satisfies the second but not the first.

Ignoring. Probably a minor thinko on his part, no big deal.

>>> Because i's the one that
>>> varies, so "i is less than ten" is more idiomatic than "ten is greater than
>>> or equal to i".
>> Why?
> 
> Because programmatically, "i" changes over time, 10 does not,

That doesn't answer the question.

> and when
> one reads out loud the controlling expression in English, the subject of
> that sentence ("the actor") should be the entity that is acting.

Again, this is C we're discussing, not English.

>>> Now consider:
>>> 	for (i = 0; i < max; ++i)
>>>
>>> even though "max" may vary over time, the assumption is that, for this loop,
>>> i changes and max doesn't.
>> Why?
> 
> Because when read out loud, "i" is the subject.

Again, your comment would only be relevant if this were English, which 
it isn't.

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 4:04:36 PM

Tim Rentsch <txr@x-alumni2.alumni.caltech.edu> writes:
> Keith Thompson <kst-u@mib.org> writes:
>
>> Ian Collins <ian-news@hotmail.com> writes:
>>> Tim Rentsch wrote:
>>>> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>>>> Anand Hariharan wrote:
>>>>>> <snip>
>>>>>>> Haven't seen anyone point this out:
>>>>>>>
>>>>>>> Rather than -
>>>>>>>
>>>>>>>   #define MAXNUMFILES 1024
>>>>>>>
>>>>>>> - prefer -
>>>>>>>
>>>>>>>   const int MaxNumFiles = 1024;
>>>>>>>
>>>>>>>
>>>>>>> That way your preprocessor won't do as much damage.
>>>>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>>>>> an array size.
>>>>> It's a problem in C99 too, if the array is defined at file scope or it
>>>>> has internal linkage.  There are other reasons why it's not a great
>>>>> idea in C99.  They stem from the fact that MaxNumFiles is not
>>>>> permitted as part of a constant expression.  [snip elaboration]
>>>>
>>>> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
>>>> expression, albeit an implementation-specific constant expression;
>>>> it just isn't _required_ to be a portable constant expression.
>>>
>>> What?  You could say just about any nonsense is permitted as part of
>>> an implementation-specific expression.
>>>
>>> That doesn't alter that fact that in C90 or C99, MaxNumFiles is not
>>> permitted as part of a constant expression.
>>
>> I think Tim is referring to C99 6.6p10:
>>
>>     An implementation may accept other forms of constant expressions.
>
> Quite so.
>
>> (I just noticed that this doesn't use the term
>> "implementation-defined" implying, I think, that an implementation
>> can accept other forms of constant expressions but isn't required
>> to document them.)
>
> My belief is that such forms of constant expressions still count
> as language extensions.  If they are they must be documented,
> because extensions are required to be documented.

Then the only purpose of 6.6p10 is to permit implementations *not* to
issue diagnostics on the use of "other forms of constant expressions".
For example:

    const int x = 42;
    switch (...) {
        case x:
    ...

Normally "case x:" is a constraint violation, but if the
implementation accepts it under 6.6p10, no diagnostic is required.
Plausible, but I'm not 100% convinced either that this is what the
standard says or that it's a good idea.  For one thing, the lack
of a diagnostic would make it more difficult to write portable code.

>> My understanding is that code that uses extensions in general (as
>> permitted by C99 4p6) still require diagnostics if the code violates a
>> constraint, but code that uses "other forms of constant expressions"
>> does not.
>
> Yes, diagnostics are still required for using any extensions that
> is a syntax error or a constraint violation, but not not if they
> don't, and that also includes "other forms of constant expressions".
> (In other words my assessment here agrees with Keith's.)

I'm not sure mine does.  Another reasonable interpretation of 6.6p10
is that it permits implementations to support other forms of constants;
for example:

    const int x = 0b10_1010;
    /* 0b denotes binary, underscores are ignored */

This is obviously a syntax error, requiring a diagnostic, for an
implementation that doesn't support it.  Can an implementation not
emit a diagnostic and point to 6.6p10 to justify it?  Or must it
issue a diagnostic and make it an extension under 4p6?

I'd be happy to accept the committee's intent here if I knew what
it was.

[snip]

>> And why is that permission there in the first place?  What benefit
>> does it really provide beyond the existing permission to provide
>> extensions?
>
> It seems clear that the point is to allow additional forms of
> constant expression without absolutely insisting on generating a
> diagnostic;  in other words to leave the question of diagnostics
> up to the discretion of the implementation.  Without 6.6p10 any
> other forms of constant expression wouldn't meet the Standard's
> definition, and if used in places that need constant expressions
> would cause constraint violations.

Personally, I'd prefer to drop the permission in 6.6p10 and allow
other forms of constant expression, like any other extension, under
4p6.  A conforming implementation would have to issue a diagnostic
for anything that would be a constraint violation or syntax error
without the extension.  If you don't want the diagnostic, invoke
the compiler in a not-quite-conforming mode.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 4:30:55 PM

Richard Heathfield  wrote in message
<4JydnbCdGNgatgzWnZ2dnUVZ7rydnZ2d@bt.com>:
> This is C we're discussing, not English. It is folly to pretend that the 
> rules of English apply to C.

The rules of the human mind, made manifest by the structure of natural
languages, should apply to any artificial language if you want it to be
readable.
0
Reply george54 (194) 3/5/2010 4:35:49 PM

In comp.lang.c Keith Thompson <kst-u@mib.org> wrote:
> William Ahern <william@wilbur.25thandClement.com> writes:
> > In comp.unix.programmer Ike Naar <ike@localhost.claranet.nl> wrote:
> [...]
> >> Using ``='' for something other than equality was, in my opinion, the
> >> most unfortunate design decision in the design of C.
> >
> > But it does mean equality. In fact, it commands it.
>
> Not for volatile objects or NaNs.

The implementation may not comply, and by the standard rightly so. But "="
is nonetheless a command by the programmer to make the object equal. "="
isn't a cognate w/ the mathemetical symbol. It's merely overloaded. C is an
imperative language, afterall.
0
Reply William 3/5/2010 5:01:53 PM

In article
<0.49be2e2b11253f6112d8.20100305151304GMT.87vddaajk0.fsf@bsb.me.uk>,
Ben Bacarisse <ben.usenet@bsb.me.uk> writes:

> lacos@ludens.elte.hu (Ersek, Laszlo) writes:
> 

>> In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>

>>> Seebs wrote:

>>>> 	for (i = 0; i < 10; ++i)
>>>> 
>>>> Why do we write "i < 10" rather than "10 >= i"?

>> "10 == i" satisfies the second but not the first.

> Either way, it's not really at the heart of the question unless you
> think the switch *caused* the typo.

Yes, I thought (and think) that that was not unpossible. If my memory
serves, both Keith and Seebs have pointed out that they need to reorder
reverse-ordered relational operators in their heads (sorry if I'm making
this up now) or that it causes extra mental load or something to that
effect. So the typo may be related to the reversing process.

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 5:09:42 PM

In article <4JydnbCdGNgatgzWnZ2dnUVZ7rydnZ2d@bt.com>,
Richard Heathfield <rjh@see.sig.invalid> writes:

> Ersek, Laszlo wrote:

>> Because when read out loud, "i" is the subject.
> 
> Again, your comment would only be relevant if this were English, which 
> it isn't.

Exactly -- I'm a staunch member of the "7 == x" camp. I just tried to
explain why, as I perceive, Seebs thinks what he thinks. (Sorry if this
qualifies as bad etiquette.)

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 5:13:51 PM

On 05/03/2010 07:18, Richard Heathfield wrote:
> [Interesting bunch of crossposts!]
>
> Keith Thompson wrote:
>> Tim Streater <timstreater@waitrose.com> writes:
>>> On 04/03/2010 20:35, Jonathan de Boyne Pollard wrote:
>>>>> And "x == 7" is much more readable than "7 == x".
>>>>>
>>>>> At least, for English speakers it is. I don't know; maybe there are
>>>>> languages in which saying "if x is equal to y" implies that x is the
>>>>> constant and y is the variable.
>>>>>
>>>> Nonsense. This is nothing to do with speaking English.
>
> Correct. C and English are different languages, with different purposes
> and different idioms.
>
>>>> You only find
>>>> the ordering natural in C for purely circular reasons: It's natural to
>>>> (most) C programmers because that's how most C language code that they
>>>> have read is written. (And it's written that way because "It's
>>>> natural.") Nothing more, and nothing as a result of the English
>>>> language.
>
> Right.
>
>>> Rubbish. You don't say "if that chicken is an animal then I'll eat
>>> it", you say "If that animal is a chicken then I'll eat it".
>
> Tim, those two sentences don't mean the same thing. We're discussing
> value equality, not (as Keith nicely puts it) set membership. Closer
> example: "if that chicken's name is Edwina, I'll eat it" vs "if Edwina
> is that chicken's name, I'll eat it".

I think my example was not, in any case, a very good one. Where I'm 
coming from is, I believe, this: an "if" statement is to be used where 
one wants to test something. If I see a statement that starts, e.g.:

   if  (7==x ...

then immediately my brain is saying: "Hold on, why am I testing 7? I 
know what 7 is equal to - it's equal to 7! So what's the "if" statement 
for?". If I want to know what *x* is equal to, that's a different story, 
and a valid question, because x is a variable. 7 is not.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/5/2010 5:22:02 PM

On 05/03/2010 16:04, Richard Heathfield wrote:
> Ersek, Laszlo wrote:
>> In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>
>>> Seebs wrote:
>>>
>>> <snip>
>>>
>>>> When I see "if (x != y)" in C, I
>>>> unconsciously perceive it to be the case that x could vary and y
>>>> couldn't.
>>> Why?
>>
>> Because he pronounces it as "x is not equal to y", and the subject of
>> that sentence is "x". "x" is the actor, the variable that is acting. "y"
>> is part of the prepositional phrase, it is static.
>
> This is C we're discussing, not English. It is folly to pretend that the
> rules of English apply to C.

But Richard, you have to read the code in order to interpret it mentally 
and decide whether it's correct or not, or how to amend it. I gave up on 
Forth, Lisp, and regexps for just this reason.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/5/2010 5:31:40 PM

Ersek, Laszlo wrote:
> In article <4JydnbCdGNgatgzWnZ2dnUVZ7rydnZ2d@bt.com>,
> Richard Heathfield <rjh@see.sig.invalid> writes:
> 
>> Ersek, Laszlo wrote:
> 
>>> Because when read out loud, "i" is the subject.
>> Again, your comment would only be relevant if this were English, which 
>> it isn't.
> 
> Exactly -- I'm a staunch member of the "7 == x" camp. I just tried to
> explain why, as I perceive, Seebs thinks what he thinks. (Sorry if this
> qualifies as bad etiquette.)

I misinterpreted your reply, and misreplied accordingly. The 
responsibility for bad etiquette in this subthread, if bad etiquette has 
indeed transpired, is entirely mine.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 5:40:21 PM

Tim Streater wrote:
> On 05/03/2010 16:04, Richard Heathfield wrote:
>> Ersek, Laszlo wrote:
>>> In article <OIidndrfAtccKg3WnZ2dnUVZ8sCdnZ2d@bt.com>,
>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>
>>>> Seebs wrote:
>>>>
>>>> <snip>
>>>>
>>>>> When I see "if (x != y)" in C, I
>>>>> unconsciously perceive it to be the case that x could vary and y
>>>>> couldn't.
>>>> Why?
>>>
>>> Because he pronounces it as "x is not equal to y", and the subject of
>>> that sentence is "x". "x" is the actor, the variable that is acting. "y"
>>> is part of the prepositional phrase, it is static.
>>
>> This is C we're discussing, not English. It is folly to pretend that the
>> rules of English apply to C.
> 
> But Richard, you have to read the code in order to interpret it mentally 
> and decide whether it's correct or not, or how to amend it.

Right. But it makes more sense to read it in C than to read it in 
English. [Analogy alert!] When deciding on the correctness of a passage 
in French or German, one should read it in French or German, not English.

Thinking in a foreign language is difficult, but that does not mean that 
the attempt should not be made when dealing with sentences written in 
that language.

> I gave up on 
> Forth, Lisp, and regexps for just this reason.

I have to confess that an utter inability to read, let alone think in, 
Whitespace led me to reject that language without even trying to write a 
single program in it. Regular expressions are actually a very good 
example (or, perhaps, are very good examples) of how translation to 
English doesn't really aid comprehension. You need to be able to think 
in regexps if you're going to use them effectively. I'm okay with simple 
regexps, but only because I've internalised them. The moment I find 
myself trying to translate them into English, I know I've lost.

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 5:48:32 PM

On Mar 5, 12:13=A0pm, la...@ludens.elte.hu (Ersek, Laszlo) wrote:
> In article <4JydnbCdGNgatgzWnZ2dnUVZ7rydn...@bt.com>,
>
> Richard Heathfield <r...@see.sig.invalid> writes:
> > Ersek, Laszlo wrote:
> >> Because when read out loud, "i" is the subject.
>
> > Again, your comment would only be relevant if this were English, which
> > it isn't.
>
> Exactly -- I'm a staunch member of the "7 =3D=3D x" camp. I just tried to
> explain why, as I perceive, Seebs thinks what he thinks. (Sorry if this
> qualifies as bad etiquette.)

Are you a staunch member of the '7 =3D=3D x' because of style, or because
of the possibility of catching '7 =3D x' errors?  I personally don't
like the style simply because it *is* more mind taxing, and it's a
result of not seeing code in that style, not writing code in that
style, and not thinking about code in that style, for about 8 years
between C++ and C, that my brain has been conditioned that way.  I
would be bold enough to say that a large majority of C programmers are
conditioned that way, simply from other people's code and books that
I've seen.

Perhaps you would allow me to scramble the characters on your keyboard
in a way of my choosing that is better?  Let's take 'asdfjkl;' and
make it 'arstenil' since those d, f, j, k, and ';' characters are used
much less often, and it requires more finger movement, causing more
cases of carpal tunnel syndrome.  Would you be willing to give that a
try?  The example is a bit hyperbolish, but that's how it feels to me
looking at '7 =3D=3D x'.

And the thing is that you may actually like that keyboard better, but
everyone else will still use the standard keyboard, and still complain
if they have to use your keyboard.  The inertia of the original style
'x =3D=3D 7' is too large enough to overcome unless that style has
generated so many problems that I'm motivated to try out '7 =3D=3D x'.  If
you suffered from carpal tunnel syndrome, you may be tempted to give
the new keyboard a try.

I actually went through this process with single line if statements.

if ( condition )
  statement;

I have been bitten by this syntax (spending hours pouring over code
where my brain is not registering the syntax error) so many times that
the bracket style

if ( condition ) {
  statement;
}

has become my convention.  It has saved me time because for whatever
reason, my brain can deal with the syntax errors better.

Lastly, I have no problem with someone wanting to use '7 =3D=3D x' if it
really does help them from a style perspective.  I have an issue when
people use the style just to catch '7 =3D x' errors when 'x =3D=3D 7' would
be easier to understand.  Hey, I still use 'char* p' simply because I
started in C++ and moved to C, and it's easier for me to use.  I'm
sure there are a host of people that will belittle me for still using
that syntax, and I realize I may be in the minority, but I'll still
keep using it since it's more work to relearn and restyle the code
I've already written than to appease the majority.

Again, if I have to work with a team, and it's decided to use 'char
*p', I will gladly acquiesce, but unless I'm forced to code that way
for a long time, I don't foresee myself changing my ways.

Best regards,
John D.

> Cheers,
> lacos

0
Reply jadill33 (201) 3/5/2010 6:03:27 PM

On 2010-03-05, Richard Heathfield <rjh@see.sig.invalid> wrote:
> Willem wrote:
>> Disagree.  The semantic difference is that the first object is the item
>> that we're interested in, and the second is something we wish to know of
>> the first.

> Not entirely convinced. In each case, we wish to know whether [Fred] and 
> [the man who shot my chicken] are the same person.

No.

In one case, we want to know what Fred did.  In the other, we want to know
what happened to the chicken.

For another example:  Consider the difference between...
	That bottle contains a liter of water.
	A liter is the amount of water in that bottle.

One is telling you something about the bottle; the other is offering a
definition of a liter.

Think of it in terms of definitions, and the relationship is clearer; when
you say "let x be any positive integer", that's not the same thing as saying
"any positive integer is x".  Descriptions don't have quite as strong a
directionality, but they still do have a noticeable polarity.

In some cases, it's not just the relationship that's being expressed, but
also something about which participants in the relationship are of interest
to us.  There is a substantial difference in focus between "the capacitor
grounded through Jim" and "Jim grounded the capacitor".  One is a statement
about the failure of an electrical device to continue working, one is a
statement about the failure of a biological device to continue working.  That
they describe the same circumstance doesn't mean they describe the same
*focus*.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:06:54 PM

On 2010-03-05, Ike Naar <ike@localhost.claranet.nl> wrote:
> In article <slrnhp1a11.hqg.usenet-nospam@guild.seebs.net>,
> Seebs  <usenet-nospam@seebs.net> wrote:
>>I disagree.  I was raised by mathematicians, but I view statements and
>>expressions as often being written to communicate additional meaning.

> But you must be careful not to assign additional meaning if it was
> unintended by the author.

You can never avoid both Type 1 and Type 2 errors completely.  For the most
part, the benefits of assuming that idioms are intentional massively outweigh
the costs of perceiving an idiom was not intended.

> If you read my code, it would be unfortunate if you would conclude, from the
> bare fact that I wrote the addition as (a+b), that a is the larger of
> the two.

And I wouldn't draw any such conclusion.  I might, however, think that a
was in some way the "base" value.

a[i] is in theory equally equivalent to both *(a+i) and *(i+a).  However,
it is EXTREMELY unusual to write i+a -- because we know that we are adding
an offset to a pointer, not adding a pointer to an offset.  That they do
the same thing doesn't matter.  The pointer is the one which tells us what
the operation is doing.

> But that perception could be misleading.

Yes, it could.

Heuristics don't have to be 100% reliable to be worth using.

> Another reason might be that "i < 10" and "10 >= i" are not the same thing.

Whoops.  >, not >=.  I'm bad at symmetry sometimes.  Or alternatively,
probably, "9 >= i".

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:11:26 PM

On 2010-03-05, Richard Heathfield <rjh@see.sig.invalid> wrote:
> I don't see how you get that y can't vary, just from seeing if(x != y). 

I don't.

I just get the impression that it is much less likely to be the member
whose value is in question.

And I'd guess that if you took a random sample of C code (say, a hundred lines
from each of a couple thousand projects), you'd find that this was true
in the VAST majority of cases.  Well over 90%.

Note that a limit like "max" is invariant *in context*, normally.

while (i < len)

usually means that, for the duration of the loop, i will be changing and len
won't.  Not always, but it's true often enough that exceptions are surprising.

> It's been done both ways before.

But one of them much, much, more often.

> Then, much of the time, you expect the wrong thing, since much of the 
> time there is no invariant involved. If you were reading my code, you 
> would very often find that, where an invariant /is/ involved in a 
> comparison for equality, it's on the left. So your preconceptions would 
> mislead you.

With your code, yes.  So I'd realize you were one of the people who does
it the other way.  Same as, if I went to England and noticed people driving
on the wrong side of the road, after a couple of hours I'd be used to that.

> I am always suspicious of "we do it this way because most people do it 
> this way". Sturgeon's Law and all that. I'm not saying we should do Y 
> *because* most people do X; but following the crowd *just* for the sake 
> of following the crowd is very often a bad idea, because the crowd is 
> very often heading in the wrong direction.

There is no significant objective advantage to either... But, as with the
side of the road, there is a substantial advantage to having everyone agree.

> Sure. So which one is the constant you were expecting to see?

Neither.  But I'm fine with a heuristic being imperfect.  They are.

It's just that, IF there is one that's more changeable than the other, I
expect it to be on the left.

>> K&R.  I don't think you'll find a single test in there which goes the
>> other way.

> That's a rather weak basis for claiming a "standard idiom".

It works for 1TBS.

And again, consider why it is that every test in K&R, and in King's book (I
believe), and anywhere else I've looked, uses the same idiom.  One of the
reasons is that, having seen it that way, people tend to expect it and write
it that way, and the net result is additional communication.

It's like indentation.  We indent code to make it reasonable.  We do not,
to borrow your phrase, "keep in mind what the brackets do with their contained
blocks" and ignore indentation conventions; we use them because presenting
things with consistent structure makes it easier for people to chunk the
information and process it effectively.

Imagine that you have two code bases, which are precisely identical, except
that in one of them, this idiom is used consistently wherever it applies, and
in the other, the first code base has been copied, and then half of the
comparisons have had their operands flipped (and the operator changed if
needed).  Now have a large number of people try to find a number of difficult
bugs in them.

I would bet you that you would notice a measurable performance cost to the
reliability and speed of debugging from losing the idiom, especially if the
tests were significant to the bugs.  It's only a few cycles here and there, or
one slot of short term memory, but sometimes that's what makes the difference
between catching something and not catching it.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:19:16 PM

On 2010-03-05, Ersek, Laszlo <lacos@ludens.elte.hu> wrote:
> ... It's either me, or now two of you not noticing (or ignoring) that
> "10 == i" satisfies the second but not the first.

I often introduce fencepost errors when I swap relationships.  No idea
why.  It's the same as my mysterious inability to learn to reliably add
single-digit numbers.  (I can do it about 95% of the time, give or take.)

> Because programmatically, "i" changes over time, 10 does not, and when
> one reads out loud the controlling expression in English, the subject of
> that sentence ("the actor") should be the entity that is acting.

That's pretty much it.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:21:07 PM

On 2010-03-05, Ersek, Laszlo <lacos@ludens.elte.hu> wrote:
> Yes, I thought (and think) that that was not unpossible. If my memory
> serves, both Keith and Seebs have pointed out that they need to reorder
> reverse-ordered relational operators in their heads (sorry if I'm making
> this up now) or that it causes extra mental load or something to that
> effect. So the typo may be related to the reversing process.

It probably is.  Actually, that's clarified it.  Here's the thing.

	(x < 10)
	!(x >= 10)

That kind of reversal requires adding/removing an =.  So if I'm flipping
a comparison relationship, I'm likely to add/remove an =.  It turns out
that merely changing the direction isn't the same thing as flipping.

	(x < 10)
	(10 > x)
	!(x >= 10)
	!(10 <= x)

.... Yup.  I got the >< in the second pair wrong on the first try, had to
go back and think about them.

I can do one flip or the other, usually, but if two of them are on offer,
I tend to screw them up.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:24:01 PM

On 2010-03-05, Richard Heathfield <rjh@see.sig.invalid> wrote:
> This is C we're discussing, not English. It is folly to pretend that the 
> rules of English apply to C.

Actually, I'm not exactly talking about English.  I'm talking about the
underlying cognitive structures English (and every other language) maps to.
So far as I know, regardless of language, humans distinguish between the
topic and the comment (thanks to another poster for providing the
terminology).

> Ignoring. Probably a minor thinko on his part, no big deal.

Not a big deal, but oddly, somewhat related -- it's the kind of mistake that
shows up as a side-effect of added complexity.  If you add enough parentheses
to an expression, people will start mismatching them or putting them in the
wrong places because they can't track them automatically anymore, or because
the automatic tracking fails.

For me, swapping the "natural" order of a comparison (I expect the "topic"
to be first) is one extra layer, similar to an indirection, extra set of
parentheses, or whatever.  I don't know how common that is, but I'm pretty
sure it's not going to change in the forseeable future.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/5/2010 6:26:41 PM

ImpalerCore <jadill33@gmail.com> writes:
> On Mar 5, 12:13 pm, la...@ludens.elte.hu (Ersek, Laszlo) wrote:
>> In article <4JydnbCdGNgatgzWnZ2dnUVZ7rydn...@bt.com>,
>>
>> Richard Heathfield <r...@see.sig.invalid> writes:
>> > Ersek, Laszlo wrote:
>> >> Because when read out loud, "i" is the subject.
>>
>> > Again, your comment would only be relevant if this were English, which
>> > it isn't.
>>
>> Exactly -- I'm a staunch member of the "7 == x" camp. I just tried to
>> explain why, as I perceive, Seebs thinks what he thinks. (Sorry if this
>> qualifies as bad etiquette.)
>
> Are you a staunch member of the '7 == x' because of style, or because
> of the possibility of catching '7 = x' errors?  I personally don't
> like the style simply because it *is* more mind taxing, and it's a
> result of not seeing code in that style, not writing code in that
> style, and not thinking about code in that style, for about 8 years
> between C++ and C, that my brain has been conditioned that way.  I
> would be bold enough to say that a large majority of C programmers are
> conditioned that way, simply from other people's code and books that
> I've seen.
[...]

I have a question for those who like and/or use the '7 == x;' style.

The usual rationale for the '7 == x' style is that it makes it
easier to catch errors where you type "=" rather than "==".

Would you even consider writing '7 == x' rather than 'x == 7'
if C's equality and comparison operators were more distinct?

For example, consider a hypothetical C-like language in which the
equality operator is spelled "=" and the assignment operator is
"<-", and "==" is a syntax error.  (Yes, that would quietly break
"x<-1"; let's ignore that.)

In such a language, would you ever write "if (7 = x)" in preference
to "if (x = 7)"?  If so, why?

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 8:18:39 PM

Keith Thompson wrote:
> 
> I have a question for those who like and/or use the '7 == x;' style.
> 
> The usual rationale for the '7 == x' style is that it makes it
> easier to catch errors where you type "=" rather than "==".

Good development practices (unit testing) will catch that typo.

> Would you even consider writing '7 == x' rather than 'x == 7'
> if C's equality and comparison operators were more distinct?
> 
> For example, consider a hypothetical C-like language in which the
> equality operator is spelled "=" and the assignment operator is
> "<-", and "==" is a syntax error.  (Yes, that would quietly break
> "x<-1"; let's ignore that.)
> 
> In such a language, would you ever write "if (7 = x)" in preference
> to "if (x = 7)"?  If so, why?

While not a programming language, most unit test harnesses (at least all 
those I've used) express test assertions as ASSERT( expected, actual ) 
so after using them for a while, placing the invariant on the left 
doesn't look so bad.  Despite many years exposure to this testing style, 
I still place the invariant on the right in conditionals....

-- 
Ian Collins
0
Reply ian-news (9878) 3/5/2010 8:28:58 PM

On 05/03/10 08:21, Casper H.S. Dik wrote:
[...]
> I'm not sure why they aren't using:
> 
> 	memset(x, ~0, sizeof (*x))
> 
> Are you talking about Solaris?

Interix, actually, although the whole proc filesystem structure (which
the code was quoted from) appears to have been lifted wholesale from
Solaris/Unixware.

-- 
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────
│
│ 𝕻𝖍'𝖓𝖌𝖑𝖚𝖎 𝖒𝖌𝖑𝖜'𝖓𝖆𝖋𝖍 𝕮𝖙𝖍𝖚𝖑𝖍𝖚
│ 𝕽'𝖑𝖞𝖊𝖍 𝖜𝖌𝖆𝖍'𝖓𝖆𝖌𝖑 𝖋𝖍𝖙𝖆𝖌𝖓.
0
Reply dg (324) 3/5/2010 8:47:27 PM

On 2010-03-05, Ersek, Laszlo <lacos@ludens.elte.hu> wrote:
>
> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>
>> lacos@ludens.elte.hu (Ersek, Laszlo) writes:
>>
>>>> Seebs wrote:
>>>>> 
>>>>> Why do we write "i < 10" rather than "10 >= i"?
>>>
>>> "10 == i" satisfies the second but not the first.
>>
>> Either way, it's not really at the heart of the question unless you
>> think the switch *caused* the typo.
>
> Yes, I thought (and think) that that was not unpossible. If my memory
> serves, both Keith and Seebs have pointed out that they need to reorder
> reverse-ordered relational operators in their heads (sorry if I'm making
> this up now) or that it causes extra mental load or something to that
> effect. So the typo may be related to the reversing process.
>

(I hope I haven't munged up the attributions; they were formatted
funnily and I was having a tough time reading them, so I shuffled
some >'s around.)

As Seebs points out in his reply to this article,
  (i > 10) == !(i <= 10),
while
  (i > 10) == (10 < i),
which is quite a different beast.

Also, the idiomatic "count up to 10" loop is:
  for(i = 0; i < 10; ++i)

while "count down to 10" is:
  for(i = 10; i >= 10; ++i)

For these reasons I didn't see the typo, even after lacos said that
there /was/ one, a fact that initially escaped me completely. Like
Keith and Seebs, I need to mentally reorder these kind of expressions
to understand them.

I do that simply by reading the words backwards, since reading and
writing backwards is much easier for me than re-ordering and then
"reading" different text from what I see. So I find it interesting
that I made the same mistake.

-- 
Andrew Poelstra
http://www.wpsoftware.net/andrew
0
Reply apoelstra (387) 3/5/2010 9:02:50 PM

In comp.unix.programmer Ike Naar <ike@localhost.claranet.nl> wrote:
> It doesn't matter, but anybody can fool themselves that it does.
> And then Alice convinces herself that 3+x is ugly and unreadable,
> Bob opts for x+3 being error-prone and unreadable, and now what
> should Carol write?

The ISO, or perhaps her elected representative - there aught to be a
law right?-)

rick jones
-- 
oxymoron n, Hummer H2 with California Save Our Coasts and Oceans plates
these opinions are mine, all mine; HP might not want them anyway... :)
feel free to post, OR email to rick.jones2 in hp.com but NOT BOTH...
0
Reply rick.jones2 (1061) 3/5/2010 9:10:01 PM

Andrew Poelstra <apoelstra@localhost.localdomain> writes:
[...]
> Also, the idiomatic "count up to 10" loop is:
>   for(i = 0; i < 10; ++i)
>
> while "count down to 10" is:
>   for(i = 10; i >= 10; ++i)

I don't think that's what you meant.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 9:14:21 PM

On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> Andrew Poelstra <apoelstra@localhost.localdomain> writes:
> [...]
>> Also, the idiomatic "count up to 10" loop is:
>>   for(i = 0; i < 10; ++i)
>>
>> while "count down to 10" is:
>>   for(i = 10; i >= 10; ++i)
>
> I don't think that's what you meant.
>

:)

for(i = 10; i >= 0; ++i)

vi makes copy/paste too easy to do without looking at the
screen.

-- 
Andrew Poelstra
http://www.wpsoftware.net/andrew
0
Reply apoelstra (387) 3/5/2010 9:27:17 PM

Andrew Poelstra <apoelstra@localhost.localdomain> writes:
> On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
>> Andrew Poelstra <apoelstra@localhost.localdomain> writes:
>> [...]
>>> Also, the idiomatic "count up to 10" loop is:
>>>   for(i = 0; i < 10; ++i)
>>>
>>> while "count down to 10" is:
>>>   for(i = 10; i >= 10; ++i)
>>
>> I don't think that's what you meant.
>>
>
> :)
>
> for(i = 10; i >= 0; ++i)
>
> vi makes copy/paste too easy to do without looking at the
> screen.

So that's counting down *from* 10, not *to* 10 (speaking of
copy/paste).

Also, the "up to 10" loop executes 10 times, for values from 0 to 9
inclusive, while the "down from 10" loop executes 11 times, for values
from 10 down to 0 inclusive.

Finally, it's an infinite loop if i is of an unsigned type.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Reply kst-u (21464) 3/5/2010 9:38:25 PM

On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> Andrew Poelstra <apoelstra@localhost.localdomain> writes:
>> On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
>>> Andrew Poelstra <apoelstra@localhost.localdomain> writes:
>>> [...]
>>>> Also, the idiomatic "count up to 10" loop is:
>>>>   for(i = 0; i < 10; ++i)
>>>>
>>>> while "count down to 10" is:
>>>>   for(i = 10; i >= 10; ++i)
>>>
>>> I don't think that's what you meant.
>>>
>>
>> :)
>>
>> for(i = 10; i >= 0; ++i)
>>
>> vi makes copy/paste too easy to do without looking at the
>> screen.
>
> So that's counting down *from* 10, not *to* 10 (speaking of
> copy/paste).
>
> Also, the "up to 10" loop executes 10 times, for values from 0 to 9
> inclusive, while the "down from 10" loop executes 11 times, for values
> from 10 down to 0 inclusive.
>
> Finally, it's an infinite loop if i is of an unsigned type.
>

Plus, I used in ++i instead of --i. My goodness.

In real life I always do:

i = 10;  /* or max, or probably max - 1 */
while(--i)
  ...


-- 
Andrew Poelstra
http://www.wpsoftware.net/andrew
0
Reply apoelstra (387) 3/5/2010 9:53:29 PM

Andrew Poelstra wrote:
> 
> On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> > Andrew Poelstra <apoelstra@localhost.localdomain> writes:
> >> On 2010-03-05, Keith Thompson <kst-u@mib.org> wrote:
> >>> Andrew Poelstra <apoelstra@localhost.localdomain> writes:
> >>> [...]
> >>>> Also, the idiomatic "count up to 10" loop is:
> >>>>   for(i = 0; i < 10; ++i)
> >>>>
> >>>> while "count down to 10" is:
> >>>>   for(i = 10; i >= 10; ++i)
> >>>
> >>> I don't think that's what you meant.
> >>>
> >>
> >> :)
> >>
> >> for(i = 10; i >= 0; ++i)
> >>
> >> vi makes copy/paste too easy to do without looking at the
> >> screen.
> >
> > So that's counting down *from* 10, not *to* 10 (speaking of
> > copy/paste).
> >
> > Also, the "up to 10" loop executes 10 times, for values from 0 to 9
> > inclusive, while the "down from 10" loop executes 11 times, for values
> > from 10 down to 0 inclusive.
> >
> > Finally, it's an infinite loop if i is of an unsigned type.
> >
> 
> Plus, I used in ++i instead of --i. My goodness.
> 
> In real life I always do:
> 
> i = 10;  /* or max, or probably max - 1 */
> while(--i)
>   ...

To count down through an array with N elements, I use

size_t i = N;

while (i-- != 0) {
    array[i];
}

-- 
pete
0
Reply pfiland (6613) 3/5/2010 10:02:19 PM

In article
<2dddfb45-b0e6-4957-9557-0507cca064cb@g26g2000yqn.googlegroups.com>,
ImpalerCore <jadill33@gmail.com> writes:

> Are you a staunch member of the '7 == x' because of style, or because
> of the possibility of catching '7 = x' errors?

It became my style after using it consciously for a while. The original
reason was the one you mention as second.


> I personally don't like the style simply because it *is* more mind taxing,
> and it's a result of not seeing code in that style, not writing code in
> that style, and not thinking about code in that style, for about 8 years
> between C++ and C, that my brain has been conditioned that way.  I would
> be bold enough to say that a large majority of C programmers are
> conditioned that way, simply from other people's code and books that I've
> seen.

I think I agree. I also think I don't care about how other people, with whom
I don't share a team, write their code :) I will not change my style just to
follow an unrelated majority.


> And the thing is that you may actually like that keyboard better, but
> everyone else will still use the standard keyboard, and still complain
> if they have to use your keyboard.

They have every reason to complain *now*, if they try to use my keyboard
:) Under Linux, I have my own keymap, under Windows, I have my own
keyboard layout dll, created with Microsoft's Keyboard Layout Creator
(available at no charge on their site).  My layout dates back to DOS,
where I modified / programmed a TSR in Turbo Pascal so I could input
accented characters *and* source code.  I touch-type (with completely
unofficial finger patterns), so when people try to look at the keyboard
for help, they are even more baffled, because I never care what "skin"
the keyboard has, as my layout is independent from that skin.


> The inertia of the original style 'x == 7' is too large enough to overcome
> unless that style has generated so many problems that I'm motivated to try
> out '7 == x'.  If you suffered from carpal tunnel syndrome, you may be
> tempted to give the new keyboard a try.

Usually, I adapt quickly to new styles if I'm convinced about their benefits
(or when I realize that I have no choice).  I didn't start out with "7 ==
x", I trained myself to write that way.  It was inconvenient first, but then
it became natural.  I picked up brace style, initialization style etc etc
the same way, gradually.  I chose to adopt them.

My touch-typing patterns are completely unofficial and QWERTY dependent
(or more precisely, dependent on my own QWERTY-derivative),*and I
luckily never suffered from RSI, so I have no incentive to try out other
keyboard styles.


> I actually went through this process with single line if statements.
> 
> if ( condition )
>   statement;
> 
> I have been bitten by this syntax (spending hours pouring over code
> where my brain is not registering the syntax error) so many times that
> the bracket style
> 
> if ( condition ) {
>   statement;
> }
> 
> has become my convention.  It has saved me time because for whatever
> reason, my brain can deal with the syntax errors better.

Same here (except no spaces around "condition" between the parentheses),
but for other reasons: I like to be able to jump to the end of the block
in my editor, and also to put a comment on the closing brace
occasionally.


> Again, if I have to work with a team, and it's decided to use 'char
> *p', I will gladly acquiesce, but unless I'm forced to code that way
> for a long time, I don't foresee myself changing my ways.

Same here. If we formalize an in-house standard (= coding style) that
prescribes "x == 7", I'll adapt.  Consistency is more important than my
idiosyncracies.

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 10:10:56 PM

In article <lnmxymsesg.fsf@nuthaus.mib.org>,
Keith Thompson <kst-u@mib.org> writes:

> Would you even consider writing '7 == x' rather than 'x == 7'
> if C's equality and comparison operators were more distinct?
> 
> For example, consider a hypothetical C-like language in which the
> equality operator is spelled "=" and the assignment operator is
> "<-", and "==" is a syntax error.  (Yes, that would quietly break
> "x<-1"; let's ignore that.)
> 
> In such a language, would you ever write "if (7 = x)" in preference
> to "if (x = 7)"?  If so, why?

No, I would not have picked up the "7 == x" style in that case.

For example, Pascal has := for assignment and = for equality (IIRC :)). Even
in C, I started out with "x == 7".  I was occasionally bitten by
"if (x = 7)" typos.  Not very frequently, and most of the time caught by
compiler warnings.  However, on some forum somebody brought up "7 == x"
explicitly, and after giving the idea my unrelenting attention :) for a
minute or two, I liked it so much that I trained myself to it.

Cheers,
lacos
0
Reply lacos (176) 3/5/2010 10:29:45 PM

pete wrote:
<snip>

> To count down through an array with N elements, I use
> 
> size_t i = N;
> 
> while (i-- != 0) {
>     array[i];
> }

Isn't this where we came in? Or was that another thread?

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/5/2010 10:38:39 PM

Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>How do you feel about i[array][j] and j[i[array]] (or, indeed,
>j[array[i]] to get the full set)?

  Of all those, �j[i[array]]� stands out as more consistent,
  since �i[array][j]� and �j[array[i]]� seems to mix both �styles�.

0
Reply ram (2825) 3/5/2010 10:53:08 PM

On 05/03/2010 22:29, Ersek, Laszlo wrote:
> In article<lnmxymsesg.fsf@nuthaus.mib.org>,
> Keith Thompson<kst-u@mib.org>  writes:
>
>> Would you even consider writing '7 == x' rather than 'x == 7'
>> if C's equality and comparison operators were more distinct?
>>
>> For example, consider a hypothetical C-like language in which the
>> equality operator is spelled "=" and the assignment operator is
>> "<-", and "==" is a syntax error.  (Yes, that would quietly break
>> "x<-1"; let's ignore that.)
>>
>> In such a language, would you ever write "if (7 = x)" in preference
>> to "if (x = 7)"?  If so, why?
>
> No, I would not have picked up the "7 == x" style in that case.
>
> For example, Pascal has := for assignment and = for equality (IIRC :)). Even
> in C, I started out with "x == 7".  I was occasionally bitten by
> "if (x = 7)" typos.  Not very frequently, and most of the time caught by
> compiler warnings.  However, on some forum somebody brought up "7 == x"
> explicitly, and after giving the idea my unrelenting attention :) for a
> minute or two, I liked it so much that I trained myself to it.

What about maintenance? Someone later will look at that and waste half a 
day trying to see if there's some reason it's written that way.

-- 
Tim

"That the freedom of speech and debates or proceedings in Parliament 
ought not to be impeached or questioned in any court or place out of 
Parliament"

Bill of Rights 1689
0
Reply timstreater (943) 3/5/2010 11:43:26 PM

Tim Streater <timstreater@waitrose.com> writes:
>What about maintenance? Someone later will look at that and waste half a 
>day trying to see if there's some reason it's written that way.

  That would be in favor of such a construct as it indicates
  that it would help to find the incompetent code reviewers.

0
Reply ram (2825) 3/6/2010 12:15:57 AM

Richard Heathfield wrote:
> 
> pete wrote:
> <snip>
> 
> > To count down through an array with N elements, I use
> >
> > size_t i = N;
> >
> > while (i-- != 0) {
> >     array[i];
> > }
> 
> Isn't this where we came in? Or was that another thread?

I remember writing the same thing once a few weeks ago
but I don't remember which thread.

-- 
pete
0
Reply pfiland (6613) 3/6/2010 12:17:08 AM

On 2010-03-06, Stefan Ram <ram@zedat.fu-berlin.de> wrote:
> Tim Streater <timstreater@waitrose.com> writes:
>>What about maintenance? Someone later will look at that and waste half a 
>>day trying to see if there's some reason it's written that way.

>   That would be in favor of such a construct as it indicates
>   that it would help to find the incompetent code reviewers.

I wouldn't spend half a day on it, but I'd at the very least check the
rest of the code to see whether it used the same idiom.

Code reviewers who don't check out deviation from idioms are not being
careful enough, IMHO.  It may be there's a good reason for it, but the most
common reasons I've seen are:

1.  The person writing the code is not very familiar with standard idioms,
and may also make common mistakes that those idioms are designed to prevent.
2.  The code DOES follow the idiom, and I misread it the first time.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/6/2010 12:41:09 AM

Richard Heathfield <rjh@see.sig.invalid> writes:
> pete wrote:
> <snip>
>
>> To count down through an array with N elements, I use
>>
>> size_t i = N;
>>
>> while (i-- != 0) {
>>     array[i];
>> }
>
> Isn't this where we came in? Or was that another thread?

Oh, don't be such an idiom!

Phil
-- 
I find the easiest thing to do is to k/f myself and just troll away
-- David Melville on r.a.s.f1
0
Reply thefatphil_demunged (1558) 3/6/2010 12:52:24 AM

In article <LeadnUHKaP2DCgzWnZ2dnUVZ8vxi4p2d@brightview.co.uk>, Tim Streater <timstreater@waitrose.com> writes:
> On 05/03/2010 22:29, Ersek, Laszlo wrote:
>> In article<lnmxymsesg.fsf@nuthaus.mib.org>,
>> Keith Thompson<kst-u@mib.org>  writes:
>>
>>> Would you even consider writing '7 == x' rather than 'x == 7'
>>> if C's equality and comparison operators were more distinct?
>>>
>>> For example, consider a hypothetical C-like language in which the
>>> equality operator is spelled "=" and the assignment operator is
>>> "<-", and "==" is a syntax error.  (Yes, that would quietly break
>>> "x<-1"; let's ignore that.)
>>>
>>> In such a language, would you ever write "if (7 = x)" in preference
>>> to "if (x = 7)"?  If so, why?
>>
>> No, I would not have picked up the "7 == x" style in that case.
>>
>> For example, Pascal has := for assignment and = for equality (IIRC :)). Even
>> in C, I started out with "x == 7".  I was occasionally bitten by
>> "if (x = 7)" typos.  Not very frequently, and most of the time caught by
>> compiler warnings.  However, on some forum somebody brought up "7 == x"
>> explicitly, and after giving the idea my unrelenting attention :) for a
>> minute or two, I liked it so much that I trained myself to it.
> 
> What about maintenance? Someone later will look at that and waste half a 
> day trying to see if there's some reason it's written that way.

You are right.

In a pro setting, I'll participate when the coding style is set, and
then I'll follow it. If no coding style is set at all, I'll have my
share of the guerilla development. I may hint at the necessity of a
coding style, but I won't fight for it, because I hate politics, and
some co-workers always take it as an attack on their authority. I help
with creating guidelines the best I can when I'm asked, but I'm no
enforcer.

In a hobbyist setting, like I've been coding C recently, I don't care.
(The word being "hobby", not "unpaid job". (Hobby doesn't imply low
quality (hopefully!), just that I'm my boss and my customer.)) I don't
code for users and I work alone. I code for myself and am happy if
others benefit too. (... Though it seems they can prod me into more
work.)

Cheers,
lacos
0
Reply lacos (176) 3/6/2010 2:01:54 AM

Ersek, Laszlo wrote:
> In article <LeadnUHKaP2DCgzWnZ2dnUVZ8vxi4p2d@brightview.co.uk>, Tim Streater <timstreater@waitrose.com> writes:
>> On 05/03/2010 22:29, Ersek, Laszlo wrote:

<snip>

>>> However, on some forum somebody brought up "7 == x"
>>> explicitly, and after giving the idea my unrelenting attention :) for a
>>> minute or two, I liked it so much that I trained myself to it.
>> What about maintenance? Someone later will look at that and waste half a 
>> day trying to see if there's some reason it's written that way.
> 
> You are right.

No, he isn't. :-)  Anyone who wastes half a day on understanding 7==x is 
not the kind of person you want maintaining C code in the first place.

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/6/2010 6:45:13 AM

On 2010-03-06, Richard Heathfield <rjh@see.sig.invalid> wrote:
> No, he isn't. :-)  Anyone who wastes half a day on understanding 7==x is 
> not the kind of person you want maintaining C code in the first place.

Not "understanding 7==x".  Figuring out whether it's been done that way for
a particular reason.  And while "half a day" may be a bit much, I've certainly
seen fairly experienced coders lose an hour or more to something that was
written in a way that suggested a deeper meaning or intent when it was, in
fact, merely idiosyncratic.

If someone wrote:
	for (i = 0; max > i; ++i)
I'd at least want to investigate briefly whether there was some non-obvious
reason for which the comparison was written backwards.  If I couldn't find
one, I'd check every comparison in the code (and a lot of other stuff) more
carefully, for much the same reason that I check code more carefully if
there's trivial misspellings in the comments.

Sometimes, the effort's wasted, but so far, my experience has been that it's
right more often than it's wrong.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/6/2010 8:39:51 AM

Seebs wrote:
> On 2010-03-06, Richard Heathfield <rjh@see.sig.invalid> wrote:
>> No, he isn't. :-)  Anyone who wastes half a day on understanding 7==x is 
>> not the kind of person you want maintaining C code in the first place.
> 
> Not "understanding 7==x".  Figuring out whether it's been done that way for
> a particular reason.

If it takes him more than a quarter of a second to recognise that the 
writer put the constant on the left to allow even the dumbest of 
compilers to alert the programmer in case he missed one of the =s (given 
that this technique is hardly a trade secret), then he's not the kind of 
person you want maintaining C code in the first place.

> And while "half a day" may be a bit much, I've certainly
> seen fairly experienced coders lose an hour or more to something that was
> written in a way that suggested a deeper meaning or intent when it was, in
> fact, merely idiosyncratic.
> 
> If someone wrote:
> 	for (i = 0; max > i; ++i)
> I'd at least want to investigate briefly whether there was some non-obvious
> reason for which the comparison was written backwards.

You say it's "backwards", and okay, obviously I believe that you see it 
that way. I /don't/ see it that way. <shrug>

<snip>

-- 
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
0
Reply rjh (10789) 3/6/2010 9:07:46 AM

On 2010-03-06, Richard Heathfield <rjh@see.sig.invalid> wrote:
> Seebs wrote:
>> Not "understanding 7==x".  Figuring out whether it's been done that way for
>> a particular reason.

> If it takes him more than a quarter of a second to recognise that the 
> writer put the constant on the left to allow even the dumbest of 
> compilers to alert the programmer in case he missed one of the =s (given 
> that this technique is hardly a trade secret), then he's not the kind of 
> person you want maintaining C code in the first place.

I disagree.  I wouldn't trust someone who made that assumption without
checking it -- at least, say, verifying that the same author did that
consistently.

I've heard of that convention, and that argument for it, but I've never seen
it actually solve a problem -- I don't think I've used a compiler in either
of the last two decades that couldn't catch such errors in other ways.  So if
I see code written that way, I check it out to see whether that's what's up.
That takes a lot more than a quarter second -- and if only one test in a file
is written that way, I'm not going to assume it was someone using that
convention, because if they did, all the other tests would be the same.

>> If someone wrote:
>> 	for (i = 0; max > i; ++i)
>> I'd at least want to investigate briefly whether there was some non-obvious
>> reason for which the comparison was written backwards.

> You say it's "backwards", and okay, obviously I believe that you see it 
> that way. I /don't/ see it that way. <shrug>

That's fine -- but since the vast majority of code writes those relations in
a consistent way, exceptions ought to be looked at.

Cases where something is done in an unusual way are often either errors
or signs of something funky up with the code.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
0
Reply usenet-nospam (2199) 3/6/2010 9:47:19 AM

"pete" <pfiland@mindspring.com> ha scritto nel messaggio
news:4B919F04.271C@mindspring.com...
> Richard Heathfield wrote:
>>
>> pete wrote:
>> <snip>
>>
>> > To count down through an array with N elements, I use
>> >
>> > size_t i = N;
>> >
>> > while (i-- != 0) {
>> >     array[i];
>> > }
>>
>> Isn't this where we came in? Or was that another thread?
>
> I remember writing the same thing once a few weeks ago
> but I don't remember which thread.

the thread i would like to prove above is not ok
but see i make wrong and i sent nothing

> -- 
> pete



0
Reply io_x 3/6/2010 10:10:34 AM

On 5 Mar 2010 23:29:45 +0100
lacos@ludens.elte.hu (Ersek, Laszlo) wrote:

> No, I would not have picked up the "7 == x" style in that case.
> 
> For example, Pascal has := for assignment and = for equality
> (IIRC :)). Even in C, I started out with "x == 7".  I was
> occasionally bitten by "if (x = 7)" typos.  Not very frequently, and
> most of the time caught by compiler warnings.  However, on some forum
> somebody brought up "7 == x" explicitly, and after giving the idea my
> unrelenting attention :) for a minute or two, I liked it so much that
> I trained myself to it.

1) The "Even in C" is in one some way related to "For example,
   Pascal..." ?

2) The fact you "liked it so much" has something to do with Pascal?

I prefer

if (x == 7)

because it gives me the idea I'm testing x more and because 90 % of the
code I've seen use that.
0
Reply vlllnz (22) 3/6/2010 1:50:59 PM

Keith Thompson <kst-u@mib.org> writes:

> Tim Rentsch <txr@x-alumni2.alumni.caltech.edu> writes:
>> Keith Thompson <kst-u@mib.org> writes:
>>
>>> Ian Collins <ian-news@hotmail.com> writes:
>>>> Tim Rentsch wrote:
>>>>> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>>>>> Richard Heathfield <rjh@see.sig.invalid> writes:
>>>>>>> Anand Hariharan wrote:
>>>>>>> <snip>
>>>>>>>> Haven't seen anyone point this out:
>>>>>>>>
>>>>>>>> Rather than -
>>>>>>>>
>>>>>>>>   #define MAXNUMFILES 1024
>>>>>>>>
>>>>>>>> - prefer -
>>>>>>>>
>>>>>>>>   const int MaxNumFiles = 1024;
>>>>>>>>
>>>>>>>>
>>>>>>>> That way your preprocessor won't do as much damage.
>>>>>>> Fine in C99, I think, but an issue in C90 if he's using it to define
>>>>>>> an array size.
>>>>>> It's a problem in C99 too, if the array is defined at file scope or it
>>>>>> has internal linkage.  There are other reasons why it's not a great
>>>>>> idea in C99.  They stem from the fact that MaxNumFiles is not
>>>>>> permitted as part of a constant expression.  [snip elaboration]
>>>>>
>>>>> Minor clarification -- MaxNumFiles is _permitted_ as part of a constant
>>>>> expression, albeit an implementation-specific constant expression;
>>>>> it just isn't _required_ to be a portable constant expression.
>>>>
>>>> What?  You could say just about any nonsense is permitted as part of
>>>> an implementation-specific expression.
>>>>
>>>> That doesn't alter that fact that in C90 or C99, MaxNumFiles is not
>>>> permitted as part of a constant expression.
>>>
>>> I think Tim is referring to C99 6.6p10:
>>>
>>>     An implementation may accept other forms of constant expressions.
>>
>> Quite so.
>>
>>> (I just noticed that this doesn't use the term
>>> "implementation-defined" implying, I think, that an implementation
>>> can accept other forms of constant expressions but isn't required
>>> to document them.)
>>
>> My belief is that such forms of constant expressions still count
>> as language extensions.  If they are they must be documented,
>> because extensions are required to be documented.
>
> Then the only purpose of 6.6p10 is to permit implementations *not* to
> issue diagnostics on the use of "other forms of constant expressions".
> For example:
>
>     const int x = 42;
>     switch (...) {
>         case x:
>     ...
>
> Normally "case x:" is a constraint violation, but if the
> implementation accepts it under 6.6p10, no diagnostic is required.
> Plausible, but I'm not 100% convinced either that this is what the
> standard says or that it's a good idea.  For one thing, the lack
> of a diagnostic would make it more difficult to write portable code.

Just three words:  quality of implementation.


>>> My understanding is that code that uses extensions in general (as
>>> permitted by C99 4p6) still require diagnostics if the code violates a
>>> constraint, but code that uses "other forms of constant expressions"
>>> does not.
>>
>> Yes, diagnostics are still required for using any extensions that
>> is a syntax error or a constraint violation, but not not if they
>> don't, and that also includes "other forms of constant expressions".
>> (In other words my assessment here agrees with Keith's.)
>
> I'm not sure mine does.  Another reasonable interpretation of 6.6p10
> is that it permits implementations to support other forms of constants;
> for example:
>
>     const int x = 0b10_1010;
>     /* 0b denotes binary, underscores are ignored */
>
> This is obviously a syntax error, requiring a diagnostic, for an
> implementation that doesn't support it.  Can an implementation not
> emit a diagnostic and point to 6.6p10 to justify it?  Or must it
> issue a diagnostic and make it an extension under 4p6?

A diagnostic must be issued.  6.6p10 doesn't give licence to
avoid giving a diagnostic, only to declare that something is
a constant expression.  It's because an expression is a constant
expression that the various CE constraints are satisfied (and
so don't need diagnostics issued for them);  but that doesn't
remove the obligation to satisfy other constraints as well.


> I'd be happy to accept the committee's intent here if I knew what
> it was.

So if you were sure that the intention was to allow other
forms of constant expressions without having to give a 
diagnostic you'd be happy with that, even though you're
not sure it's a good idea?  Or were you talking just about
the specific question of new kinds of constants?


>>> And why is that permission there in the first place?  What benefit
>>> does it really provide beyond the existing permission to provide
>>> extensions?
>>
>> It seems clear that the point is to allow additional forms of
>> constant expression without absolutely insisting on generating a
>> diagnostic;  in other words to leave the question of diagnostics
>> up to the discretion of the implementation.  Without 6.6p10 any
>> other forms of constant expression wouldn't meet the Standard's
>> definition, and if used in places that need constant expressions
>> would cause constraint violations.
>
> Personally, I'd prefer to drop the permission in 6.6p10 and allow
> other forms of constant expression, like any other extension, under
> 4p6.  A conforming implementation would have to issue a diagnostic
> for anything that would be a constraint violation or syntax error
> without the extension.  If you don't want the diagnostic, invoke
> the compiler in a not-quite-conforming mode.

I think that's a bad idea, because I always want to invoke my
compilers in conforming modes (I essentially always use -pedantic,
for example).  If I'm forced to use a non-conforming mode, who know
what other kinds of non-conformance might be introduced?  I would
rather have my compiler always be conforming, and have the option
for getting warnings or errors on use of implementation-specific
forms of constant expression.  6.6p10 lets implementations do that.
0
Reply txr2511 (42) 3/6/2010 2:05:25 PM

Tim Streater <timstreater@waitrose.com> writes:

> On 03/03/2010 01:11, Tim Rentsch wrote:
>> Tim Streater<timstreater@waitrose.com>  writes:
>
>>> My preferred approach is to do like this:
>>>
>>> function wiggy ()
>>>       {
>>>       if (cond)
>>>            {
>>>            dostuff;
>>>            }
>>>       else {
>>>            dootherstuff;
>>>            }
>>>       }
>>>
>>> This has been my approach ever since I was writing BCPL in the 70s -
>>> it has the braces lining up so that the matching can be seen easily.
>>
>> Does this mean you've never tried alternate approaches since then?
>> Did you try any other approaches earlier?
>
> I didn't use any such structured language before then. Well, that's
> not quite true. We had Algol, Snobol, Lisp and perhaps some others on
> my post-grad CS course in the late 60s, but I went to CERN after that
> where everything was, perforce, FORTRAN.

So you're saying you've really only ever tried this one
bracing style?  That you haven't tried out any others
even just to get a sense of what they might be like?
0
Reply txr2511 (42) 3/6/2010 2:09:33 PM