473,396 Members | 2,121 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

what is difference between sizeof and strlen

hello,
what is difference between sizeof("abcd") and strlen("abcd")? why
both functions gives different output when applied to same string
"abcd".
I tried following example for that.
#include <stdio.h>
#include <string.h>
void main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
printf("%d %d %d",strlen(str1),strlen(str2),strlen("abcd"));
}

Nov 15 '05
83 15498
In article <dd**********@yin.interaccess.com>,
Kenny McCormack <ga*****@interaccess.com> wrote:
Probably not relevant to *you*


I would have thought it was obvious that I meant relevant to the
behaviour and correctness of C implementations, not to any one person.

-- Richard
Nov 15 '05 #51
ga*****@yin.interaccess.com (Kenny McCormack) writes:
[...]
The content of this ng is religious in the sense that it has to do with the
contents of a document - and, by extension, the goings on of the minds of
the individuals who wrote that document. Science, on the other hand, is
concerned with physical phenomena - things that are, in theory at least,
verifyable by physical experimentation. So, in terms of science, someone
can say "I've tested it - I've convinced myself - void main() works just
fine" (*). Then religion comes along and says "No, it doesn't work - you
cannot trust your senses. The document [sacred text] says it does not
work". This is the essence of religion.

I think the point is not so much that any particular thing (such as that
which is currently under discussion) is a matter of religion as that the
entire scope and charter of this ng is much more in line with a religious
framework than that of a scientific one.

And that's a strange thing to find in an ng under the comp.* hierarchy.

(*) Equivalently: "They do move".


No.

What we do in this newsgroup isn't "science" in the sense of
formulating hypotheses and theories and testing them by performing
experiments in the real world and observing the results.

It's more like mathematics, in which we start from a set of postulates
and rules of inference and reason from them to reach conclusions.

As far as "void main" is concerned, the standard does *not* say that
it doesn't "work". To see what it does say, read any number of
articles in this thread -- or read the standard itself.

Arguing about whether void main() "works" in comp.lang.c is not unlike
arguing about whether parallel lines can meet in Euclidean geometry.
It is a fact that parallel lines cannot meet in Euclidean geometry,
because that's one of the postulates on which it's built. It's also a
fact that "parallel" lines can meet in some non-Euclidean geometries
-- but then you're not talking about Euclidean geometry anymore.

It is, of course, possible to discuss the relationship between
Euclidean geometry and the real world (is space curved?), but strictly
speaking that's not a discussion about Euclidean geometry. Similarly,
it's possible to discuss the relationship between C and the real world
(does gcc conform to this section of the standard?), but again,
strictly speaking that's not a discussion of C, which is what this
newsgroup is about.

C is intended to be useful, of course, which is why the standard (the
set of postulates from which we work) is designed to be both
implementable (by compiler writers) and usable (by programmers).

(If I were to concede that C is a religion, we'd merely being doing
the equivalent of asking people to discuss their blasphemies *outside*
the church doors so they don't interrupt the service. But I make no
such concession.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #52
Anton Petrusevich <ca***@att-ltd.biz> writes:
Keith Thompson wrote:
and since the latter is portable, there is no advantage in using the
former.


Good point. This is just my experience that says me: "I have never seen a C
compiler which generated different symbols for void main() and for int
main()". And so in my mind it's not a big deal which defenition to use.


The advantage of staying within the limits defined by the standard
whenever possible is that you don't have to depend on your own
experience. If "void main()" has always worked for you in the past,
it could break tomorrow, and if you complain to your compiler vendor,
all he has to do is point to the standard. If you use "int main()"
and your program breaks, either something else is responsible for it
or you've found a compiler bug that the vendor had better fix if he
wants any repeat business.
There's nothing religious about it. It's a matter of correctness
about which there are strong feelings, largely because certain people
and/or institutions have encouraged something that is incorrect for no
good reason.


If you would call ANSI/ISO C standard as "Bible"... :)


Only jokingly.

The standard is a contract between implementers and programmers. It's
binding only on those who choose to accept it (or who are required to
do so by, say, their employers). There's no legal penalty for writing
a non-conforming compiler or a non-conforming program, but there are
real benefits to conformance. In this newsgroup, we usually take that
as given rather than continually re-explaining *why* it's good to have
a standard.
Perhaps the word "religious" doesn't mean what you think
it means. (And if you want to discuss that further, please take it to
alt.usage.english.)


Is my English so bad?


Not at all, and if I had stopped to realize that you're probably not a
native speaker of English, I would have phrased that differently. (It
was also a reference to a line from the movie "The Princess Bride".)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #53
On Mon, 08 Aug 2005 22:12:28 +0200, Anton Petrusevich
<ca***@att-ltd.biz> wrote:
Keith Thompson wrote:
and since the latter is portable, there is no advantage in using the
former.


Good point. This is just my experience that says me: "I have never seen a C
compiler which generated different symbols for void main() and for int
main()". And so in my mind it's not a big deal which defenition to use.


It's not necessarily different symbols, it could be different code
generated. For instance, it might insist on return values being passed
back on the stack, so that for a function returning int it would do a
POP to get the return value but not for a void function -- if your void
main doesn't put that value on the stack the calling routine will try to
pop something which isn't there, possibly causing a system crash.
There's nothing religious about it. It's a matter of correctness
about which there are strong feelings, largely because certain people
and/or institutions have encouraged something that is incorrect for no
good reason.


If you would call ANSI/ISO C standard as "Bible"... :)


I don't. I regard it the same way as a Health and Safety handbook -- if
you do things the way it says then you will be safe. If you don't,
you are on your own and better be very certain why you are doing it in a
different way. Not just "it saves typing a line".
Perhaps the word "religious" doesn't mean what you think
it means. (And if you want to discuss that further, please take it to
alt.usage.english.)


Is my English so bad?


Not at all, it's better than most of the people who post to Usenet who
claim to be native English speakers (most of the errors you make look
like typos rather than lack of knowledge of English, and I make enough
of those that I can't criticise that!). However, native speakers of
English don't always understand the words they use properly either or
they use them in ways they weren't supposed to mean (especially
politicians and journalists -- you seem too sensible to be either of
those <g>) and "religious" is one of those over-used and wrongly used
words. So is "Bible", the word does literally mean just "book" but with
capital letter at start it refers to a specific book and shouldn't be
used casually to mean "any book I respect and follow" (indeed, the
Christian Bible would be madness to follow as literally as we do the C
standard!).

Chris C
Nov 15 '05 #54
ga*****@yin.interaccess.com (Kenny McCormack) wrote:
I'm going to say this briefly and hope that the more intelligent readers
can fill in the blanks and not worry about the lack of all the lawyerly
bells and whistles that are ordinarily necessary.
I could put that even more briefly, but in the interest of civility I
won't.
The content of this ng is religious in the sense that it has to do with the
contents of a document


The law is religious? Literature? Seems to me that you should go see a
real church from the inside, to know what you're talking about.

Richard
Nov 15 '05 #55
Kenny McCormack wrote:
The content of this ng is religious in the sense that it has to do with
the contents of a document - and, by extension, the goings on of the minds
of
the individuals who wrote that document. Science, on the other hand, is
concerned with physical phenomena - things that are, in theory at least,
verifyable by physical experimentation. So, in terms of science, someone
can say "I've tested it - I've convinced myself - void main() works just
fine" (*). Then religion comes along and says "No, it doesn't work - you
cannot trust your senses. The document [sacred text] says it does not
work". This is the essence of religion.
The document says that there is no obligation on the part of an implementor
to make `void main` "work" (whatever that means), so don't do it if you
want predictable results. This is not religion: it's contract law. Or
engineering.

Suppose, for example, that your local by-laws prevent you from running
a business from your home. You are free to experiment with running such
a business. You may even make a profit. However, should TPTB discover your
activities, you may experience undefined behaviour.

Suppose that you're building some circuit, and a 10-ohm resistance is
required [1]. You use a 7-ohm resistor, since your daughter used the last
10-ohm resistor yesterday as an earring, and you know from experience
that this "works". When this particular 7-ohm beast turns out to be at
the low end of the range and the smoke gets out and the circuit fails
in an embarassing (perhaps dangerous) fashion ...
I think the point is not so much that any particular thing (such as that
which is currently under discussion) is a matter of religion as that the
entire scope and charter of this ng is much more in line with a religious
framework than that of a scientific one.


Computer science isn't a science; we already knew this.

Now, if you want /religious/ arguments, indentation, tab-size, global
variables, ncspellingOfVariableNames, i++ vs ++i vs i += 1, for(;;) vs
while(1), &co, all seem to be waiting, fuel-soaked and steaming gently,
in the wings.

[1] All figures made up.

--
Chris "electric hedgehog" Dollin
Stross won one! Farah won one! Langford won TWO!
Nov 15 '05 #56
Anton Petrusevich wrote on 08/08/05 :
void main()

^^^^
Why do so many people post without
c) learning the first thing about C from even the most basic textbook?


What if I do not care about the return value of the program?


Who is 'I' ? AFAIK, 'I' is the system. You have no control on it.
Returning an undefined value to the system invokes an undefined
behaviour. Period.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"
Nov 15 '05 #57
Emmanuel Delahaye wrote:
What if I do not care about the return value of the program?

Who is 'I' ? AFAIK, 'I' is the system. You have no control on it.
Returning an undefined value to the system invokes an undefined
behaviour. Period.


It (the behaviour) can be perfectly defined for some particular system. The
system just returns (undefined) & 255 to the process which executed the
program. And then this process reads that (undefined) octet and happily
throws it away. I am not interested in this discussion anymore.
--
Anton Petrusevich
Nov 15 '05 #58
Anton Petrusevich wrote:
Martin Ambuhl wrote:
void main()

^^^^
Why do so many people post without
c) learning the first thing about C from even the most basic textbook?


What if I do not care about the return value of the program? Or better,
what if I _do_ care but use exit(0)?


The Standard doesn't say what a `void main` might mean, so using it
isn't portable. It doesn't matter whether or not you call `exit`,
as far as I can tell.

--
Chris "electric hedgehog" Dollin
Stross won one! Farah won one! Langford won TWO!
Nov 15 '05 #59
Anton Petrusevich wrote on 08/08/05 :
"Undefined behaviour" is a technical term in the C standard. It's not
really relevant whether *you* would call it that.


I don't get it. I thought, and I still continue to think, that "undefined
behaviour" means just that: when the behaviour is undefined. If the
behaviour is dependent on some defined thing (platform) then it's
"defined". You (or I) just need to know the platform. Of course, there's no
such (defined) thing as "platform" in C standard, so they say "undefined
behaviour". "int main()" is a tough religion, isn't it?


No matter what you think. Just stick to the facts. The C standard
defines a number of behaviours. Some others are clearly under the
responsability of the implementation (implementation-dependent). The
rest is simply 'undefined'. It's a fact. Period. There is nothing
really to argue about it.

What is undefined can do anything. The result is not predictable and
not reproducable. It's a bug. Period.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

I once asked an expert COBOL programmer, how to
declare local variables in COBOL, the reply was:
"what is a local variable?"
Nov 15 '05 #60
"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> writes:
Anton Petrusevich wrote on 08/08/05 :
"Undefined behaviour" is a technical term in the C standard. It's not
really relevant whether *you* would call it that.


I don't get it. I thought, and I still continue to think, that "undefined
behaviour" means just that: when the behaviour is undefined. If the
behaviour is dependent on some defined thing (platform) then it's
"defined". You (or I) just need to know the platform. Of course, there's no
such (defined) thing as "platform" in C standard, so they say "undefined
behaviour". "int main()" is a tough religion, isn't it?


No matter what you think. Just stick to the facts. The C standard
defines a number of behaviours. Some others are clearly under the
responsability of the implementation (implementation-dependent). The
rest is simply 'undefined'. It's a fact. Period. There is nothing
really to argue about it.

What is undefined can do anything. The result is not predictable and
not reproducable. It's a bug. Period.


To clarify (and disagree slightly) ...

The phrase "undefined behavior", as used in this newsgroup, refers to
behavior that is not defined by the C standard. Such behavior might
or might not be defined by something else (the hardware, some
secondary standard, or whatever).

As far as the C standard is concerned, code that exhibits undefined
behavior can do anything; we jokingly talk about it making demons fly
out your nose. This doesn't mean that nasal demons are a real
possibility, just that if demons *do* fly out your nose it doesn't
mean the C implementation is non-conforming.

In some cases, it can make sense to do something that's UB as far as
the C standard is concerned, *if* you have some other guarantee that
it will behave as you expect. You just need to be aware that the code
is non-portable -- and you should probably spend some time thinking
about whether there's a portable way to do it (sometimes there isn't).

For example, a union of a double and a struct containing carefully
defined bitfields can be a good way to get at the components of a
floating-point variable (sign, exponent, mantissa) -- but only at the
risk of having the code break when you port it, or when you upgrade to
a new compiler, or when your sysadmin upgrades your compiler behind
your back.

In other cases, undefined behavior is truly dangerous with no
corresponding benefit. For example, gets() cannot be used safely; it
will overflow your input buffer at the whim of the user.

It can also be useful to understand the *likely* consequences of
particular forms of undefined behavior, in general or for a particular
platform. An example I've mentioned here before is void main(); it
invokes undefined behavior, and it should be corrected, but if your
program is blowing up on line 137 you should also look elsewhere for
the cause.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #61
Chris Dollin <ke**@hpl.hp.com> writes:
Now, if you want /religious/ arguments, indentation, tab-size, global
variables, ncspellingOfVariableNames, i++ vs ++i vs i += 1, for(;;) vs
while(1), &co, all seem to be waiting, fuel-soaked and steaming gently,
in the wings.


Discussions about formatting and layout (not to mention the
others) often take on a "religious" tone, but they don't
have to. As an example consider the question of where to
put closing braces. Here are two common alternatives:
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice A */
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice B */
(To simplify the question we consider only these two
choices, and ignore the question of where to put the opening
brace; please imagine opening braces to be placed where
ever you believe they are most appropriate.)

Which choice do you prefer and why?

If your answer is along the lines of "choice A looks more
natural to me, so I write using choice A" -- that's a
statement that has a good chance of leading to a "religious"
argument.

If your answer is along the lines of "choice B is what I'm
used to, and choice A looks funny, so of course I write
using choice B (muttering 'any sensible person would') --
that's a statement that has a good chance of leading to a
"religious" argument.

If your answer is along the lines of "there have been
studies done on this question, and all the studies I'm aware
of have concluded that choice B has lower error rates;
lower errors rates are clearly beneficial, and I write using
choice B for that reason" -- that's a statement that is less
likely to lead to a "religious" argument.

If your answer is along the lines of "our in-house coding
standards mandate use of choice A; I don't have any
preference for either choice, except that I prefer to keep
my job, so I write using choice A" -- that's a statement
that is less likely to lead to a "religious" argument (even
if it might be less than completely satisfactory for other
reasons).

We've all heard and read so many times (including even the
original K&R) statements to the effect that questions of
style are just personal preference, and can't be resolved
one way or the other, that we accept these statements as
fact. Worse, whenever there is an unresolvable difference
in minor programming choices, it often gets chalked up as a
"style preference". I don't mean to suggest that there is
always a single "right" answer; to the contrary, different
people have different weighting functions for the costs and
benefits of various style guidelines (or other development
practices) and a choice that's a net win for me might very
well turn out to be a net loss for one of my co-workers.

However, we can try to be objective about what the costs and
benefits are for different choices; if the C&B are person
dependent, so be it, but those statements also can be made
objective. The main thing is attitude. If someone insists
on saying nothing more than "choice X seems right to me"
then that someone is encouraging "religious" discussion.
Conversely, trying to find a rational basis for choices
made, and to be objective about both the costs and the
benefits of each of the different choices possible, is more
likely to lead to shared understanding of what choices to
make, and why.

The C development community is both very diverse and (I
believe) very emphatic in their opinions, both individual
and collective; hence the comments here are especially
important for developers working in C.
Nov 15 '05 #62
"Style" should aid readability. Translate those marks into words and
punctuation and see how it reads.

For instance:
var++;
or
++var;

Translated into English:
"var increment."
vs.
"increment var."

--
---------------------------------------------------------------------
DataGet & PocketLog www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------

"Tim Rentsch" <tx*@alumnus.caltech.edu> wrote in message
news:kf****************@alumnus.caltech.edu...
Chris Dollin <ke**@hpl.hp.com> writes:
Now, if you want /religious/ arguments, indentation, tab-size, global
variables, ncspellingOfVariableNames, i++ vs ++i vs i += 1, for(;;) vs
while(1), &co, all seem to be waiting, fuel-soaked and steaming gently,
in the wings.


Discussions about formatting and layout (not to mention the
others) often take on a "religious" tone, but they don't
have to. As an example consider the question of where to
put closing braces. Here are two common alternatives:
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice A */
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice B */
(To simplify the question we consider only these two
choices, and ignore the question of where to put the opening
brace; please imagine opening braces to be placed where
ever you believe they are most appropriate.)

Which choice do you prefer and why?

If your answer is along the lines of "choice A looks more
natural to me, so I write using choice A" -- that's a
statement that has a good chance of leading to a "religious"
argument.

If your answer is along the lines of "choice B is what I'm
used to, and choice A looks funny, so of course I write
using choice B (muttering 'any sensible person would') --
that's a statement that has a good chance of leading to a
"religious" argument.

If your answer is along the lines of "there have been
studies done on this question, and all the studies I'm aware
of have concluded that choice B has lower error rates;
lower errors rates are clearly beneficial, and I write using
choice B for that reason" -- that's a statement that is less
likely to lead to a "religious" argument.

If your answer is along the lines of "our in-house coding
standards mandate use of choice A; I don't have any
preference for either choice, except that I prefer to keep
my job, so I write using choice A" -- that's a statement
that is less likely to lead to a "religious" argument (even
if it might be less than completely satisfactory for other
reasons).

We've all heard and read so many times (including even the
original K&R) statements to the effect that questions of
style are just personal preference, and can't be resolved
one way or the other, that we accept these statements as
fact. Worse, whenever there is an unresolvable difference
in minor programming choices, it often gets chalked up as a
"style preference". I don't mean to suggest that there is
always a single "right" answer; to the contrary, different
people have different weighting functions for the costs and
benefits of various style guidelines (or other development
practices) and a choice that's a net win for me might very
well turn out to be a net loss for one of my co-workers.

However, we can try to be objective about what the costs and
benefits are for different choices; if the C&B are person
dependent, so be it, but those statements also can be made
objective. The main thing is attitude. If someone insists
on saying nothing more than "choice X seems right to me"
then that someone is encouraging "religious" discussion.
Conversely, trying to find a rational basis for choices
made, and to be objective about both the costs and the
benefits of each of the different choices possible, is more
likely to lead to shared understanding of what choices to
make, and why.

The C development community is both very diverse and (I
believe) very emphatic in their opinions, both individual
and collective; hence the comments here are especially
important for developers working in C.

Nov 15 '05 #63
In article <11*************@corp.supernews.com>,
Baxter <lb**************@baxcode.com> wrote:
"Style" should aid readability. Translate those marks into words and
punctuation and see how it reads.

For instance:
var++;
or
++var;

Translated into English:
"var increment."
vs.
"increment var."


But you haven't translated it, you have just transliterated it according
to your idiosyncratic correspondence between C tokens and English
words. I don't use such a transliteration, so I don't find the difference
in readability you suggest.

-- Richard
Nov 15 '05 #64

[Heavily snipped for the sake of concision; hopefully I've retained
the flavor of Tim's post.]

In article <kf****************@alumnus.caltech.edu>, Tim Rentsch <tx*@alumnus.caltech.edu> writes:

As an example consider the question of where to put closing braces....

Which choice do you prefer and why?

... "choice A looks more natural to me, so I write using choice A"
[is likely to lead to a religious argument]

"choice B is what I'm used to, and choice A looks funny, so of
course I write using choice B" [religious]

"there have been studies done on this question, and all the studies
I'm aware of have concluded that choice B has lower error rates"
[less religious]

"our in-house coding standards mandate use of choice A"
[less religious]


True, and there are other possible answers with varying degrees of
subjectivity. For example, I use vi-derived editors; those editors
have useful commands for finding braces in the first column, so I
always write functions with their opening and closing braces in the
first column. That particular choice is not especially subjective,
though my choice of tool is.

Because my function-body braces are indented at the same level as
their "controlling" line of code, I also like to indent opening and
closing braces for control structures at the same level as their
controlling line. That *is* subjective, but I have a slightly
stronger justification for it (consistency) than a simple "it looks
better to me".

Obviously, though, deciding "how subjective" any of these arguments
are (or even what metric to use for gauging subjectivity) is itself a
subjective matter. So while I think many of us can agree that there
are some reasons for style choices which are less idiosyncratic and
more rational than others, arriving at a consensus on how to rank
specific reasons could be difficult.

I don't think that means the question should just be abandoned - I
still find it interesting - but it is a difficulty.

--
Michael Wojcik mi************@microfocus.com

Push up the bottom with your finger, it will puffy and makes stand up.
-- instructions for "swan" from an origami kit
Nov 15 '05 #65
Baxter said:
"Style" should aid readability. Translate those marks into words and
punctuation and see how it reads.

For instance:
var++;
This reads "var plus plus" to me.
or
++var;


And that reads "plus plus var".

Really, that's how I say them in my head thing. I have no particular
preference of one over the other in places where either may be used. In
C++, I would tend (paradoxically!) to use ++var, and I suspect this is
rubbing off in my C code too, even though I don't use C++ terribly often
and thus have little reason to develop this "habit".

--
Richard Heathfield
"Usenet is a strange place" - dmr 29 July 1999
http://www.cpax.org.uk
Email rjh at the above domain

Nov 15 '05 #66
ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <11*************@corp.supernews.com>,
Baxter <lb**************@baxcode.com> wrote:
"Style" should aid readability. Translate those marks into words and
punctuation and see how it reads.

For instance:
var++;
or
++var;

Translated into English:
"var increment."
vs.
"increment var."


But you haven't translated it, you have just transliterated it according
to your idiosyncratic correspondence between C tokens and English
words. I don't use such a transliteration, so I don't find the difference
in readability you suggest.


The important thing is that he explained his metric. This
particular metric may be somewhat person-dependent, and you
might think it's not an especially good metric for measuring
readability, but at least we know what it is.

The problem with the response is it doesn't counter-propose
a different metric. If all you say is "I don't find it
readable", that moves the discussion in the direction of
being more "religious". Conversely, to move the discussion
in the direction of being less "religious", suggest a
different metric. Sometimes this requires a bit of
introspection to discover what qualities are important. But
however you come up with one, if you want the discussion to
stay in the rational half plane rather than the "religious"
half plane, it's important to offer another metric for
consideration.

By the way, I don't think using "increment" for '++' is
especially idiosyncratic. I expect many C developers might
say something along these lines, and essentially all would
understand it if they heard it or read it. But that's
incidental to the main point about proposing another metric
in response.
Nov 15 '05 #67

"Tim Rentsch" <tx*@alumnus.caltech.edu> wrote in message

By the way, I don't think using "increment" for '++' is
especially idiosyncratic. I expect many C developers might
say something along these lines, and essentially all would
understand it if they heard it or read it. But that's
incidental to the main point about proposing another metric
in response.


"++" is known as the "increment operator". It can be either prefix or
postfix.

--
---------------------------------------------------------------------
DataGet & PocketLog www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------


Nov 15 '05 #68
Tim Rentsch wrote:
Chris Dollin <ke**@hpl.hp.com> writes:

Now, if you want /religious/ arguments, indentation, tab-size, global
variables, ncspellingOfVariableNames, i++ vs ++i vs i += 1, for(;;) vs
while(1), &co, all seem to be waiting, fuel-soaked and steaming gently,
in the wings.

Discussions about formatting and layout (not to mention the
others) often take on a "religious" tone, but they don't
have to. As an example consider the question of where to
put closing braces. Here are two common alternatives:
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice A */
if/for/while ...
... body line goes here ...
... another body line goes here ...
...
} /* choice B */


With tools like GNU Indent the whitespace issues of coding style is not
very important as the code can be transformed to anyones liking.

August
Nov 15 '05 #69
Richard Heathfield <in*****@invalid.invalid> wrote:
Baxter said:
"Style" should aid readability. Translate those marks into words and
punctuation and see how it reads.

For instance:
var++;


This reads "var plus plus" to me.
or
++var;


And that reads "plus plus var".

Really, that's how I say them in my head thing.


YAMeAICM5Euros.

Richard
Nov 15 '05 #70
> "Baxter" <lb**************@baxcode.com> wrote in message
news:11*************@corp.supernews.com...
"Style" should aid readability. Translate those marks into words andpunctuation and see how it reads.

For instance:
var++;
or
++var;

Translated into English:
"var increment."
vs.
"increment var."

"Tim Rentsch" <tx*@alumnus.caltech.edu> wrote in message


By the way, I don't think using "increment" for '++' is
especially idiosyncratic. I expect many C developers might
say something along these lines, and essentially all would
understand it if they heard it or read it. But that's
incidental to the main point about proposing another metric
in response.


"++" is known as the "increment operator". It can be either prefix or
postfix.


I don't like postfix on a single variable. I always see it as:
var++ : Do nothing with var, then increment var before the next
instruction.

Instead of just doing what you are there to do:
++var : Increment var.

No need to wait until after "var;" is executed (a null operation), IMO.

--
Mabden
Nov 15 '05 #71

In article <ot*********************@newsc.telia.net>, akarl <fu********@comhem.se> writes:

With tools like GNU Indent the whitespace issues of coding style is not
very important as the code can be transformed to anyones liking.


This plays havoc with typical source-code change control mechanisms,
as it produces a vast number of non-substantive changes, which in
turn makes it difficult to identify the substantive ones. While
the change control software will happily deal with a revision where
90% of the lines have changed, human maintainers will not.

--
Michael Wojcik mi************@microfocus.com

Q: What is the derivation and meaning of the name Erwin?
A: It is English from the Anglo-Saxon and means Tariff Act of 1909.
-- Columbus (Ohio) Citizen
Nov 15 '05 #72
Michael Wojcik said:

In article <ot*********************@newsc.telia.net>, akarl
<fu********@comhem.se> writes:

With tools like GNU Indent the whitespace issues of coding style is not
very important as the code can be transformed to anyones liking.


This plays havoc with typical source-code change control mechanisms,
as it produces a vast number of non-substantive changes, which in
turn makes it difficult to identify the substantive ones.


Well, that's easily fixed. On checking out, you indent the code to your
liking. Before checking in, you indent it to the house style. Problem
solved.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29 July 1999
http://www.cpax.org.uk
Email rjh at the above domain

Nov 15 '05 #73
mw*****@newsguy.com (Michael Wojcik) writes:
[Heavily snipped for the sake of concision; hopefully I've retained
the flavor of Tim's post.]

In article <kf****************@alumnus.caltech.edu>, Tim Rentsch <tx*@alumnus.caltech.edu> writes:

As an example consider the question of where to put closing braces....

Which choice do you prefer and why?

... "choice A looks more natural to me, so I write using choice A"
[is likely to lead to a religious argument]

"choice B is what I'm used to, and choice A looks funny, so of
course I write using choice B" [religious]

"there have been studies done on this question, and all the studies
I'm aware of have concluded that choice B has lower error rates"
[less religious]

"our in-house coding standards mandate use of choice A"
[less religious]
True, and there are other possible answers with varying degrees of
subjectivity. For example, I use vi-derived editors; those editors
have useful commands for finding braces in the first column, so I
always write functions with their opening and closing braces in the
first column. That particular choice is not especially subjective,
though my choice of tool is.


I would put this under the heading of "increased productivity."
Putting function open braces at the left edge is a better match
to your tools, and so allows you to write code faster (or write
code at the same rate, but with less effort, which is almost the
same thing).

Because my function-body braces are indented at the same level as
their "controlling" line of code, I also like to indent opening and
closing braces for control structures at the same level as their
controlling line. That *is* subjective, but I have a slightly
stronger justification for it (consistency) than a simple "it looks
better to me".
Other things being equal, more consistent expression is normally
better, again because more consistency usually translates into
increased productivity.

Of course there is the qualifying phrase, "other things being
equal". For myself I find that putting opening braces on lines
by themselves lowers my productivity, both because my eyes have
to work a little bit harder skipping the extra vertical space
and because my hands and fingers have to work a little bit
harder doing "page turning" (scrolling commands). It's also
possible (less common, but possible) to put a line of code on
the same line as an open brace, which doesn't use any extra
vertical space. I find this form also lowers my productivity
somewhat, although for different reasons; the most obvious is
what work needs to be done in an editor when cutting/pasting,
etc. I haven't done objective measurements; I'm confident
though that objective measurements would bear out my informal
observations.

In this particular area, consistency has moved me in the other
direction: open braces for functions go just after the close
parenthesis following the function parameters. This placement
seems more consistent with K&R-style placement; given how other
braces are placed in K&R, I suspect they would have put braces
at the end of the line with function parameters if the
ANSI-style function prototypes had been used in the original
language. I don't usually use vi-based tools, so that isn't a
factor for me. It seems to me that some vi-based tools offer
some degree of extensibility/programmability; can commands be
added that know how to deal with function braces placed at the
end of the line for function parameters?

Obviously, though, deciding "how subjective" any of these arguments
are (or even what metric to use for gauging subjectivity) is itself a
subjective matter. So while I think many of us can agree that there
are some reasons for style choices which are less idiosyncratic and
more rational than others, arriving at a consensus on how to rank
specific reasons could be difficult.
There are two factors: what is the metric, and is the metric
"any good"? Sometimes there are multiple metrics, in which
case some sort of weighting function of the different metrics
is taken; this situation can be thought of as just one larger,
more elaborate, metric.

The first question, "what is the metric?", is most often
answered in one of three ways: increased productivity, lower
defect rate, or better expression of programmer intent. (The
expression of programmer intent usually is expected to yield
improvements in the other areas, either directly, or indirectly
through improved team morale, lower turnover, or other similar
factors.) Each of these can be measured, and measured fairly
objectively. Note that the "expression of programmer intent"
needs to be measured relative to the set of people who will be
reading the code in question, perhaps by having questionnaire
surveys done; but still it can be measured.

The second question, "is the metric any good?", isn't an
objective question, and doesn't have to be. Whether a metric is
good or not depends on the goals of the group or company writing
the software, and those goals can change from company to
company, or even in the same company over time or from project
to project. Naturally we would like there to be agreement that
a particular metric is the right choice; even without that,
however, there is great value in having shared understanding of
what metric is to be followed, or what metrics are being
proposed. The key first step is to make the metrics explicit
rather than left as unstated assumptions.

I don't think that means the question should just be abandoned - I
still find it interesting - but it is a difficulty.


Certainly it's difficult to reach unanimous agreement or even
just consensus. What I think is the important point is that
making the metrics objective and explicit allows the discussion
to proceed, rather than get stalled as often happens otherwise.
Nov 15 '05 #74
Richard Heathfield <in*****@invalid.invalid> writes:
On checking out, you indent the code to your
liking. Before checking in, you indent it to the house style. Problem
solved.


Does anyone do this in practice? I have not, but I suspect that
it would lead to a large number of whitespace-only changes,
because adherence to style is not normally done religiously.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 15 '05 #75
>> On checking out, you indent the code to your
liking. Before checking in, you indent it to the house style. Problem
solved.


Does anyone do this in practice? I have not, but I suspect that
it would lead to a large number of whitespace-only changes,
because adherence to style is not normally done religiously.


CVS can be made to do things like re-indenting code on the way IN
and/or OUT of the repository, automatically. It would seem (but I
haven't tested this) that "cvs diff" (without -b) between the
working copy and the repository would pick up a lot of whitespace-only
changes, but diffs between two checked-in versions would not.

I don't use this feature, largely because it messes up imported
distributions (submitting diffs or bug reports based on re-indented
source code won't get much attention).

Gordon L. Burditt
Nov 15 '05 #76

"Tim Rentsch" <tx*@alumnus.caltech.edu> wrote in message
news:kf*************@alumnus.caltech.edu...
mw*****@newsguy.com (Michael Wojcik) writes: <even bigger snips than tim made> In this particular area, consistency has moved me in the other
direction: open braces for functions go just after the close
parenthesis following the function parameters. This placement
seems more consistent with K&R-style placement; given how other
braces are placed in K&R, I suspect they would have put braces
at the end of the line with function parameters if the
ANSI-style function prototypes had been used in the original
language. I don't usually use vi-based tools, so that isn't a
factor for me. It seems to me that some vi-based tools offer
some degree of extensibility/programmability; can commands be
added that know how to deal with function braces placed at the
end of the line for function parameters?


Not sure about vi-tools, but in the past I had used 'Brief' exclusively
to write code, and one of Brief's many features was that it
automatically indexed function definitions (ctrl-g brought up the
index and you could select and jump to the definition) In order
for the indexing to happen by default, the closing paren had to be
the last character on the line... opening brace could be preceded
by whitespace on the next line, but it could not be on the same line
as the parameters. I only mention Brief because it too was a very
popular editor (now emulated by microsoft's vc++) used by
many programmers, and yes, it was fully customizable, you could
program it do (with macros) anything you wanted... including
modifying the 'routines' macro to support your particular style.
Then again, it was much easier to adapt (or in my case, fashion)
one's style according to the default rules set forth by brief, and though
I did do some tweaking to the default settings, I never messed with the
routines macro as I personally liked the style they supported by default
which happened to also be compatible with FreeBSD's (man) 'style' specs!

Mark
Nov 15 '05 #77
"Mark B" <so***@localbar.com> wrote in message
news:BB*******************@monger.newsread.com...

"Tim Rentsch" <tx*@alumnus.caltech.edu> wrote in message
news:kf*************@alumnus.caltech.edu...
mw*****@newsguy.com (Michael Wojcik) writes: <even bigger snips than tim made>
In this particular area, consistency has moved me in the other
direction: open braces for functions go just after the close
parenthesis following the function parameters. This placement
seems more consistent with K&R-style placement; given how other
braces are placed in K&R, I suspect they would have put braces
at the end of the line with function parameters if the
ANSI-style function prototypes had been used in the original
language. I don't usually use vi-based tools, so that isn't a
factor for me. It seems to me that some vi-based tools offer
some degree of extensibility/programmability; can commands be
added that know how to deal with function braces placed at the
end of the line for function parameters?


Not sure about vi-tools, but in the past I had used 'Brief'

exclusively to write code, and one of Brief's many features was that it
automatically indexed function definitions (ctrl-g brought up the
index and you could select and jump to the definition) In order
for the indexing to happen by default, the closing paren had to be
the last character on the line... opening brace could be preceded
by whitespace on the next line, but it could not be on the same line
as the parameters. I only mention Brief because it too was a very
popular editor (now emulated by microsoft's vc++) used by
many programmers, and yes, it was fully customizable, you could
program it do (with macros) anything you wanted... including
modifying the 'routines' macro to support your particular style.
Then again, it was much easier to adapt (or in my case, fashion)
one's style according to the default rules set forth by brief, and though I did do some tweaking to the default settings, I never messed with the routines macro as I personally liked the style they supported by default which happened to also be compatible with FreeBSD's (man) 'style'

specs!

I still keep a copy of Brief around for DOS editing. I remember it from
when it was written by a company called Underware, before Sage bought
it. The last version I have is 3.1 which was put out by Borland of all
people.

Its coding style was so good it was easy to get all the programmer to
agree to "just do it like Brief". It ended a lot of religious wars just
by being a reasonable standard.

--
Mabden
Nov 15 '05 #78
Tim Rentsch <tx*@alumnus.caltech.edu> wrote:
The important thing is that he explained his metric. This
particular metric may be somewhat person-dependent, and you
might think it's not an especially good metric for measuring
readability, but at least we know what it is.

The problem with the response is it doesn't counter-propose
a different metric. If all you say is "I don't find it
readable", that moves the discussion in the direction of
being more "religious".


It does? May I remark that I find your usage of the word "religious"
less than optimally readable?

Richard
Nov 15 '05 #79
"Mabden" <mabden@sbc_global.net> wrote:
I don't like postfix on a single variable. I always see it as:
var++ : Do nothing with var, then increment var before the next
instruction.

Instead of just doing what you are there to do:
++var : Increment var.

No need to wait until after "var;" is executed (a null operation), IMO.


You are, of course, free to prefer one style over another as you please;
but in this case, your reasons for doing so are entirely fictitious.
There is no wait whatsoever in var++ that is not also present in ++var.
It seems that you do not understand how these operators work.

Richard
Nov 15 '05 #80
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Tim Rentsch <tx*@alumnus.caltech.edu> wrote:
The important thing is that he explained his metric. This
particular metric may be somewhat person-dependent, and you
might think it's not an especially good metric for measuring
readability, but at least we know what it is.

The problem with the response is it doesn't counter-propose
a different metric. If all you say is "I don't find it
readable", that moves the discussion in the direction of
being more "religious".


It does? May I remark that I find your usage of the word "religious"
less than optimally readable?


Certainly! I use the term "religious" only because
everyone else seems to understand it. But please
feel free to suggest something better.

Nov 15 '05 #81
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:43***************@news.xs4all.nl...
"Mabden" <mabden@sbc_global.net> wrote:
I don't like postfix on a single variable. I always see it as:
var++ : Do nothing with var, then increment var before the next
instruction.

Instead of just doing what you are there to do:
++var : Increment var.

No need to wait until after "var;" is executed (a null operation),
IMO.
You are, of course, free to prefer one style over another as you please; but in this case, your reasons for doing so are entirely fictitious.
There is no wait whatsoever in var++ that is not also present in ++var. It seems that you do not understand how these operators work.

I just said that that is the way it "scans" to me. That's where the
words "I always see it as" differ from "the computer will take 3 less
cycles to perform this operation". I see it as "do nothing" then
increment, but that does not mean I think the computer sits there
wasting cycles. When I said "no need to wait".. I didn't really mean the
computer actually waits. I meant it as a way of thinking about prefix
and postfix. Sorry for the confusion, I should have reread that.

Besides, a compiler should drop a statement like "null;" as a do-nothing
statement anyhow.

It's kinda like how I prefer for (;;) which reads as "forever", better
than while (1) since "while one" doesn't really click with anything in
my mind.

That is what style is all about.

--
Mabden
Nov 15 '05 #82

In article <de**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com>, Richard Heathfield <in*****@invalid.invalid> writes:
Michael Wojcik said:
In article <ot*********************@newsc.telia.net>, akarl
<fu********@comhem.se> writes:

With tools like GNU Indent the whitespace issues of coding style is not
very important as the code can be transformed to anyones liking.


This plays havoc with typical source-code change control mechanisms,
as it produces a vast number of non-substantive changes, which in
turn makes it difficult to identify the substantive ones.


Well, that's easily fixed. On checking out, you indent the code to your
liking. Before checking in, you indent it to the house style. Problem
solved.


I suspect that in practice this would not work well, but I happily
admit that I have not tried it.

It does suggest the interesting possiblity of using some intermediate
representation for the repository, so that only "significant" changes
are preserved. Determining what changes are significant could be
difficult, however. At times I deviate from my normal use of
whitespace when another arrangement seems clearer in a particular
case; such a scheme would lose that information.

--
Michael Wojcik mi************@microfocus.com

Painful lark, labouring to rise!
The solemn mallet says:
In the grave's slot
he lies. We rot. -- Basil Bunting
Nov 15 '05 #83

In article <kf*************@alumnus.caltech.edu>, Tim Rentsch <tx*@alumnus.caltech.edu> writes:
mw*****@newsguy.com (Michael Wojcik) writes:
In article <kf****************@alumnus.caltech.edu>, Tim Rentsch <tx*@alumnus.caltech.edu> writes:

As an example consider the question of where to put closing braces....
True, and there are other possible answers with varying degrees of
subjectivity. For example, I use vi-derived editors; those editors
have useful commands for finding braces in the first column, so I
always write functions with their opening and closing braces in the
first column.


I would put this under the heading of "increased productivity."
Putting function open braces at the left edge is a better match
to your tools, and so allows you to write code faster (or write
code at the same rate, but with less effort, which is almost the
same thing).


A fair analysis.
Because my function-body braces are indented at the same level as
their "controlling" line of code, I also like to indent opening and
closing braces for control structures at the same level as their
controlling line.


Other things being equal, more consistent expression is normally
better, again because more consistency usually translates into
increased productivity.

Of course there is the qualifying phrase, "other things being
equal". For myself I find that putting opening braces on lines
by themselves lowers my productivity, both because my eyes have
to work a little bit harder skipping the extra vertical space
and because my hands and fingers have to work a little bit
harder doing "page turning" (scrolling commands).


A plausible argument. Obviously it can be taken to extremes (the
same charges can be levelled against vertical whitespace, for
example), but I think that only shows that the cost and benefit of
vertical spacing of various elements depends on the individual
reader.

I use small fonts and large windows, and consequently I find that
vertical space is not usually a scarce resource when I work on my
own code; and so the cost of a separate line for each opening or
closing brace is relatively small for me. On the other hand, I
like ample whitespace and visual separation of control structures,
so the benefit is correspondingly greater.
In this particular area, consistency has moved me in the other
direction: open braces for functions go just after the close
parenthesis following the function parameters. ...
I don't usually use vi-based tools, so that isn't a
factor for me. It seems to me that some vi-based tools offer
some degree of extensibility/programmability; can commands be
added that know how to deal with function braces placed at the
end of the line for function parameters?
Yes, at least for any reasonably modern vi-based editor. It would
be relatively easy to change the "next function" and "previous
function" operators from a search for a brace in the first column
to a search for a brace at the outermost nesting level, regardless
of where it is on the line. (That would also find such things as
file-scope structure definitions, but then so do the current
operators, if you put their opening brace in the first column.)
The first question, "what is the metric?", is most often
answered in one of three ways: increased productivity, lower
defect rate, or better expression of programmer intent.
I suspect you could boil these three factors down into one:
define productivity as a function of feature implementation rate
versus defect rate, and assume (or demonstrate) that better
expression of intent correlates with better productivity in
maintenance work (which, in most cases, seems to dominate total
programming over the long term).

I agree those can be measured to some degree of confidence. I
imagine the real struggle would be convincing all your developers
that the metric and measurements are valid, and that a demonstrated
improvement in results justifies changing their habits. (We can't
expect everyone to be reasonable...)
Naturally we would like there to be agreement that
a particular metric is the right choice; even without that,
however, there is great value in having shared understanding of
what metric is to be followed, or what metrics are being
proposed. The key first step is to make the metrics explicit
rather than left as unstated assumptions.


I agree, particularly with the final point.

I'd also note that one aspect of Derek Jones' _The New C Standard_
(discussed recently in other threads) that I particularly like is
his ample citations of studies of programmer productivity, as
justifications for his comments about using C in particular ways.

--
Michael Wojcik mi************@microfocus.com

Auden often writes like Disney. Like Disney, he knows the shape of beasts --
(& incidently he, too, might have a company of artists producing his lines) --
unlike Lawrence, he does not know what shapes or motivates these beasts.
-- Dylan Thomas
Nov 15 '05 #84

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

Similar topics

16
by: Alfonso Morra | last post by:
Hi, I am at the end of my tether now - after spending several days trying to figure how to do this. I have finally written a simple "proof of concept" program to test serializing a structure...
10
by: Trevor | last post by:
If I have a string that should be NULL terminated, is it good practice to use "sizeof(str)" or "sizeof(str) - 1" when using a function like strncpy? If I have a 'string' that should NOT be NULL...
11
by: D | last post by:
hi, i would like to know how to calculate the size of a dynamic array created using a dereference declaration like int *numbers and allocating via malloc or calloc: numbers=(int...
11
by: Alfonso Morra | last post by:
Hi, I am at the end of my tether now - after spending several days trying to figure how to do this. I have finally written a simple "proof of concept" program to test serializing a structure...
3
by: Alfonso Morra | last post by:
Hi, I am at the end of my tether now - after spending several days trying to figure how to do this. I have finally written a simple "proof of concept" program to test serializing a structure...
35
by: Sunil | last post by:
Hi all, I am using gcc compiler in linux.I compiled a small program int main() { printf("char : %d\n",sizeof(char)); printf("unsigned char : ...
24
by: Massimo Soricetti | last post by:
Think for a moment: IF you were Bjarne Stroustrup in 1985 (or whenever he were doing it) writing down C++, and knowing all you know NOW of the C++ language, (pro, cons, features of today...
5
by: Jens | last post by:
Hello, I have been looking for some C-code which listens on a user-defined port for incoming data traffic. When data is received, the data is written to a file. I found some C-code (server)...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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

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