473,387 Members | 1,463 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,387 software developers and data experts.

++i vs i++

asm
Hi All,

I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.

Does it really matter for assignments?

Thanks,
Arut
Nov 14 '05 #1
59 27323
asm <ar**@post.com> scribbled the following:
Hi All, I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help. Does it really matter for assignments?


Yes it matters. Consider j=++i and j=i++. In both cases i gets
incremented by one. However, the value of j is one more in the former
case than in the latter case.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"'It can be easily shown that' means 'I saw a proof of this once (which I didn't
understand) which I can no longer remember'."
- A maths teacher
Nov 14 '05 #2
asm wrote:
I would like to know when ++i should be used instead of i++ and vice
versa.
Use ++i when you want the incremented value of i, and i++ when you
want the original value of i.

If you don't care which value you get, use either (although then I
switch to `i += 1`).
Does it really matter for assignments?


Yes, it really matters.

--
Chris "electric hedgehog" Dollin
C FAQs at: http://www.faqs.org/faqs/by-newsgrou...mp.lang.c.html
C welcome: http://www.angelfire.com/ms3/bchambl...me_to_clc.html
Nov 14 '05 #3
ar**@post.com (asm) writes:
Hi All,

I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.


In terms of speed there is a difference. If you look at iterators:
They are highlevel objects that support the ++ in post(i++) and
prefix(++i) form, but for the postfiz form the hole object needs to be
copied two times, one time for storing the old value and another tie for
returning the old value.

IMHO if you don't need the behaviour of the postfix form, use the prefix
form.

Kind regrads,
Nicolas

--
| Nicolas Pavlidis | Elvis Presly: |\ |__ |
| Student of SE & KM | "Into the goto" | \|__| |
| pa****@sbox.tugraz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
Nov 14 '05 #4
Nicolas Pavlidis <pa****@sbox.tugraz.at> scribbled the following:
ar**@post.com (asm) writes:
Hi All,

I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.
In terms of speed there is a difference. If you look at iterators:
They are highlevel objects that support the ++ in post(i++) and
prefix(++i) form, but for the postfiz form the hole object needs to be
copied two times, one time for storing the old value and another tie for
returning the old value.


This is an implementation detail and not mandated by the standard. The
compiler may implement the operators in any way it wants as long as the
result is the same as the standard defines.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"He said: 'I'm not Elvis'. Who else but Elvis could have said that?"
- ALF
Nov 14 '05 #5
Hi Nicolas,

I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.


In terms of speed there is a difference. If you look at iterators:
They are highlevel objects that support the ++ in post(i++) and
prefix(++i) form, but for the postfiz form the hole object needs to be
copied two times, one time for storing the old value and another tie for
returning the old value.

IMHO if you don't need the behaviour of the postfix form, use the prefix
form.


<OT>
It depends. If for example the processor has a register reserved
for the stack pointer and a rather small instruction set, then it is
possible that only postincrement and predecrement are built-in,
as they are entirely sufficient.

As it was some years ago and only a couple of weeks' pastime, I am not
exactly sure but I think I recall that for one of the M68...
processors.
</OT>

Apart from that assembler stuff, most compilers nowadays are
sufficiently "intelligent" to use the same code for the three
statements
i++;
++i;
i+=1;
when you are obviously not interested in any side effects.
Cheers
Michael

Nov 14 '05 #6
Nicolas Pavlidis <pa****@sbox.tugraz.at> wrote:
ar**@post.com (asm) writes:
I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.


In terms of speed there is a difference. If you look at iterators:
They are highlevel objects that support the ++ in post(i++) and
prefix(++i) form, but for the postfiz form the hole object needs to be
copied two times, one time for storing the old value and another tie for
returning the old value.


Erm... bullshit. This is comp.lang.c, not comp.lang.++c.

Richard
Nov 14 '05 #7
Richard Bos <rl*@hoekstra-uitgeverij.nl> scribbled the following:
Nicolas Pavlidis <pa****@sbox.tugraz.at> wrote:
In terms of speed there is a difference. If you look at iterators:
They are highlevel objects that support the ++ in post(i++) and
prefix(++i) form, but for the postfiz form the hole object needs to be
copied two times, one time for storing the old value and another tie for
returning the old value.
Erm... bullshit. This is comp.lang.c, not comp.lang.++c.

^^^

Heh. I wish I had thought of that.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"This is a personnel commuter."
- Train driver in Scientific American
Nov 14 '05 #8
In <c8**************************@posting.google.com > ar**@post.com (asm) writes:
I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.
You don't need any code examples, once you understand the difference
between the prefix increment and the postfix increment operator.

Being operators, their evaluation must yield a value. The postfix
increment operator yields the value of its operand. The prefix increment
operator yields the incremented value of its operand. As a *side effect*,
both operators increment the value of their operand, at some, unspecified,
point before the next sequence point.

When they are used exclusively for their side effects (their value
is discarded), it doesn't matter which operator is used.
Does it really matter for assignments?


The above should answer this question.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #9

"asm" <ar**@post.com> wrote

I would like to know when ++i should be used instead of i++ and vice versa. Some code examples would be of help.

Does it really matter for assignments?

In C, the form i++ is idiomatic. The form ++i really shouldn't be used. It
increments i before calculating the value of i, which is almost never
required. Even if it would be handy, its use will confuse maintaining
programmers. If ++i would make an expression more compact, break it down
into two lines instead.

However in C++, because of a quirk of the language, the form ++C is faster
than the form C++ for overloaded types with complex logic. Here the ++C form
should be used.
Nov 14 '05 #10

"asm" <ar**@post.com> wrote in message
news:c8**************************@posting.google.c om...
Hi All,

I would like to know when ++i should be used instead of i++ and vice versa. Some code examples would be of help.
int x,
y;
int i = 5;
x = i++;
y = ++i;

Does it really matter for assignments?


Not sure, I never submit my assignments on time.

--
ISA
Nov 14 '05 #11
Malcolm <ma*****@55bank.freeserve.co.uk> spoke thus:
In C, the form i++ is idiomatic. The form ++i really shouldn't be used. It
increments i before calculating the value of i, which is almost never
required. Even if it would be handy, its use will confuse maintaining
programmers. If ++i would make an expression more compact, break it down
into two lines instead.


How will ++i confuse anyone who knows what s/he is doing? I'm far
from an expert, and I certainly don't find it confusing.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #12
Malcolm wrote:
"asm" <ar**@post.com> wrote
I would like to know when ++i should be used instead of i++ and vice
versa.
Some code examples would be of help.

Does it really matter for assignments?


In C, the form i++ is idiomatic. The form ++i really shouldn't be used. It
increments i before calculating the value of i, which is almost never
required. Even if it would be handy, its use will confuse maintaining
programmers. If ++i would make an expression more compact, break it down
into two lines instead.


Have you been smoking those funny cigarettes again, Malcolm? It's
unlike you to make such idioTmatic remarks ... I'd be interested to
know what other C operators you think "shouldn't be used," and on what
grounds, however shaky. I'm sure it'd be amusing.
However in C++, because of a quirk of the language, the form ++C is faster
than the form C++ for overloaded types with complex logic. Here the ++C form
should be used.


Another (and equally compelling) reason to avoid both the `++c' and
`c++' forms is that they're syntax errors in Pascal.

--
Er*********@sun.com
Nov 14 '05 #13
Malcolm wrote:

"asm" <ar**@post.com> wrote

I would like to know when ++i should
be used instead of i++ and vice versa.
Some code examples would be of help.

Does it really matter for assignments?
In C, the form i++ is idiomatic.
The form ++i really shouldn't be used.


I disagree.
It increments i before calculating the value of i,
which is almost never required.
No it doesn't.
The expressions (++i) and (i++) have values and side effects.
The side effect is that the value in i is increased by 1.
The value of (i++) is the value before the increment and
the value of (++i) is the value after the increment,
but whether the increment or the evaluation takes place first,
is not part of C.
Even if it would be handy, its use will confuse maintaining
programmers.
Does it really confuse you?
If ++i would make an expression more compact,
break it down into two lines instead.

However in C++, because of a quirk of the language,
the form ++C is faster than the form C++
for overloaded types with complex logic.
You're off topic and I don't believe you.
Here the ++C form should be used.


I disagree.

--
pete
Nov 14 '05 #14
pete <pf*****@mindspring.com> writes:
Malcolm wrote:

[...]
However in C++, because of a quirk of the language,
the form ++C is faster than the form C++
for overloaded types with complex logic.


You're off topic and I don't believe you.
Here the ++C form should be used.


I disagree.


Please note the '[OT]' tag in the subject. I'm discussing this here
partly to contrast C++ vs. C.

In C++, the "++" operator can be overloaded so it invokes a
user-defined function; the meaning of "increment" is determined by the
function itself, and can involve arbitrarily complex computations.

For x++, the result is the value of x before it's "incremented". In
some cases, that means that previous value of x has to be saved
somewhere, then x is "incremented", then the saved value becomes the
value of the expression. For a user-defined type, this can introduce
significant overhead, and it can be difficult for the compiler to
optimize it away. For ++x, the value of x is "incremented" and the
result is the new value of x; the old value doesn't have to be saved.

There may also be some differences between C and C++ regarding whether
the result is an lvalue; I don't remember the details.

For C, neither x++ nor ++x can invoke a user-defined function, so the
compiler is better able to optimize the expression. For any decent C
compiler, there should be no difference between x++ and ++x if the
result is discarded (e.g., if it's used as an expression statement).
(The same is probably true in C++ for predefined types.) If the
result *is* used, x++ and ++x are semantically different; choosing the
wrong one will, at best, give you a wrong answer more quickly.

--
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 14 '05 #15
asm wrote:
I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.


As a practical matter, you should almost never use either of these
except on a line by itself, in which case it doesn't matter. The
reasoning behind this claim is that it's difficult to read statements
using these operators and they can always be pulled out into a separate
statement. Here are some examples of pulling them out:

*p1++ = *p2++;
....becomes...
*p1 = *p2;
p1++; p2++;

while(*++p) { ... }
....becomes...
for(p++; *p; p++) { ... }

x = 2 + f(*p++);
....becomes...
temp = 2 + f(*p);
p++;
x = temp;

I would claim that the revised examples above are all clearer than their
briefer counterparts. Not even a novice has to stop and think about what
order things are happening in; the lexical order reflects the execution
order. Remember, your code should be boring and obvious, not sacrificing
clarity for brevity. Also don't forget that increments are a quick way
to get yourself into trouble with undefined behavior if you're not
careful, as in:

x = *p++ + *p++;

This yields UB. What was probably intended here was the straightforward:

x = *p;
p++;
x += *p;
p++;

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #16
> while(*++p) { ... }
...becomes...
for(p++; *p; p++) { ... }

Personally, I find the first one easier to read.
Remember, your code should be boring and obvious, not sacrificing
clarity for brevity.


It's all subjective to who the code's audience is. To experienced
programmers, operators like '++' become second nature. And consider:

(*p).
vs
p->

Which is more readable and which is used more often?
Nov 14 '05 #17
Keith Thompson wrote:
For any decent C
compiler, there should be no difference between x++ and ++x if the
result is discarded (e.g., if it's used as an expression statement).
(The same is probably true in C++ for predefined types.)


I'd like to point out that the expression (i-- != 1)
is semantically equal to (--i != 0), (except where i is a pointer)
meaning that any implementation might translate those two
expressions identically. I would be more likely to use the second
expression in source code, than the first.

--
pete
Nov 14 '05 #18
Method Man wrote:
It's all subjective to who the code's audience is. To experienced
programmers, operators like '++' become second nature.
Keep in mind that not every programmer who maintains your code may be an
expert, or be an expert who is particular lucid at the time (under high
stress, low on sleep, hangover, etc.) To experienced programmers,
assembly language is second nature, but that doesn't mean we prefer it.
And consider:
(*p). vs p->
Which is more readable and which is used more often?


The important thing is that lexical order reflects execution order. In
this case you can read "p->" as a single conceptual operation with
chooses a member from the object p refers to. The choice of * as a
prefix rather than a postfix operator is arbitrary (although in this
case needed to automatically parse things correctly). This is
effectively a local transformation, unlike ++, which can potentially be
transmitted across an arbitrarily long string of tokens, as in this example:

b = a++ + /* one-million token expression */;
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #19
In <41*********@mindspring.com> pete <pf*****@mindspring.com> writes:
I'd like to point out that the expression (i-- != 1)
is semantically equal to (--i != 0), (except where i is a pointer)
meaning that any implementation might translate those two
expressions identically. I would be more likely to use the second
expression in source code, than the first.


If the comparison against 1 makes more sense (in context), I'd use
(i-- != 1). The best version in such cases is the one best reflecting
the algorithm being implemented or the programmer's intentions.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #20
Hiho,

It's all subjective to who the code's audience is. To experienced
programmers, operators like '++' become second nature. And consider:

(*p).
vs
p->

Which is more readable and which is used more often?


The second and again the second -- why?
Seriously:

Depends. I have one "favourite" line to type in when debugging
with ddd some places in the code where you can see errors coming
from other places:
graph display t->tr.n[0]->myvertex->iv.x[0]@2
displaying the first two entries of an array residing in
a structure residing in a union pointed to from a structure
pointed to from a structure residing in a union t is pointing
to. I find this nicer than
graph display ((*(*((*t).tr).n[0]).myvertex).iv).x[0]@2

I admit -> takes more time to take in intuitively but then
you see at once what is meant.
Cheers
Michael

Nov 14 '05 #21
On Fri, 24 Sep 2004 11:13:36 GMT
pete <pf*****@mindspring.com> wrote:
Keith Thompson wrote:
For any decent C
compiler, there should be no difference between x++ and ++x if the
result is discarded (e.g., if it's used as an expression statement).
(The same is probably true in C++ for predefined types.)
I'd like to point out that the expression (i-- != 1)
is semantically equal to (--i != 0), (except where i is a pointer)
meaning that any implementation might translate those two
expressions identically.


No they aren't. In one you are comparing against the value i has BEFORE
it is decremented and in the other you are comparing against the value i
has AFTER it is decremented.
I would be more likely to use the second
expression in source code, than the first.


I that case I suspect that you would misinterpret what the first form is
doing.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #22

"Derrick Coetzee" <dc****@moonflare.com> wrote in message
news:cj**********@news-int.gatech.edu...
Method Man wrote:
It's all subjective to who the code's audience is. To experienced
programmers, operators like '++' become second nature.
Keep in mind that not every programmer who maintains your code may be an
expert, or be an expert who is particular lucid at the time (under high
stress, low on sleep, hangover, etc.) To experienced programmers,
assembly language is second nature, but that doesn't mean we prefer it.
And consider:
(*p). vs p->
Which is more readable and which is used more often?


The important thing is that lexical order reflects execution order. In
this case you can read "p->" as a single conceptual operation with
chooses a member from the object p refers to. The choice of * as a
prefix rather than a postfix operator is arbitrary (although in this
case needed to automatically parse things correctly). This is
effectively a local transformation, unlike ++, which can potentially be
transmitted across an arbitrarily long string of tokens, as in this

example:
b = a++ + /* one-million token expression */;
--


The example I gave was not intended to be related to pre/post fixing of
operators. The point was simply to illustrate that code can be _subjective_
to those who read it.

ProgrammerA might consider a 'for' loop easier to read than a 'while' loop,
whereas programmerB might think the opposite in the exact same code
semantics. So which way is more "boring and obvious"?

Of couse there are many other examples, but I'll return to '++'. As I said,
I personally find 'while(*++p) { ... }' easier to read than 'for(p++; *p;
p++) { ... }'. In other cases, you're right in that I would find p++ easier
to read than ++p. It just depends and my own programming experience in C/C++
has a lot to do with it.
Nov 14 '05 #23
Michael Mair wrote:
graph display t->tr.n[0]->myvertex->iv.x[0]@2
graph display ((*(*((*t).tr).n[0]).myvertex).iv).x[0]@2


This is actually a great example of what I mean (not that I think you're
trying to contradict me, but just as an aside). In the abstract C
machine, the dereference operation *follows* the operand to which it
applies in execution order. Effectively, [0] is the postfix version of
*. In the SPECS C++ syntax (see _A Modest Proposal: C++ Resyntaxed_),
where ^ is a postfix dereference operator, the above expression would be
written like this:

t^.tr.n^^.myvertex^.iv.x^

We don't need arrows, [0], or parentheses this way, just one postfix
dereference operator. I think it's pretty neat.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #24
Flash Gordon <sp**@flash-gordon.me.uk> writes:
On Fri, 24 Sep 2004 11:13:36 GMT
pete <pf*****@mindspring.com> wrote:
Keith Thompson wrote:
> For any decent C
> compiler, there should be no difference between x++ and ++x if the
> result is discarded (e.g., if it's used as an expression statement).
> (The same is probably true in C++ for predefined types.)


I'd like to point out that the expression (i-- != 1)
is semantically equal to (--i != 0), (except where i is a pointer)
meaning that any implementation might translate those two
expressions identically.


No they aren't. In one you are comparing against the value i has BEFORE
it is decremented and in the other you are comparing against the value i
has AFTER it is decremented.


Right, but they're comparing against different values:

(i-- != 1)
(--i != 0)

so, as far as I can tell, they're equivalent (assuming that i is an
integer; due to roundoff, they can also be different if i is a
floating-point object). A sufficiently clever compiler could well
generate the same code for both. (Unless you can think of a type and
value for i for which they're different, excluding cases that invoke
undefined behavior.)

--
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 14 '05 #25
On Fri, 24 Sep 2004 15:27:02 +0100
Flash Gordon <sp**@flash-gordon.me.uk> wrote:
On Fri, 24 Sep 2004 11:13:36 GMT
pete <pf*****@mindspring.com> wrote:
Keith Thompson wrote:
For any decent C
compiler, there should be no difference between x++ and ++x if the
result is discarded (e.g., if it's used as an expression
statement).(The same is probably true in C++ for predefined
types.)


I'd like to point out that the expression (i-- != 1)
is semantically equal to (--i != 0), (except where i is a pointer)
meaning that any implementation might translate those two
expressions identically.


No they aren't. In one you are comparing against the value i has
BEFORE it is decremented and in the other you are comparing against
the value i has AFTER it is decremented.


Oops. I just realised you were testing against different values. Ignore
me.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #26

"Eric Sosman" <er*********@sun.com> wrote
In C, the form i++ is idiomatic. The form ++i really shouldn't be used.


Have you been smoking those funny cigarettes again, Malcolm? It's
unlike you to make such idioTmatic remarks ... I'd be interested to
know what other C operators you think "shouldn't be used," and on what
grounds, however shaky. I'm sure it'd be amusing.

The other baddy is the conditon ? x : y operator. It doesn't mean anything
to someone who doesn't know C (but is maybe a skilled programmer in another
language, and is forced to maintain your C program by circumstance), and
usually if() ... else would be clearer.
However the use in macros is legitimate, and also sometimes if many
conditions are tested then it can lead to a more intuitive code layout.

++i doesn't have such redeeming features. The form should be banned, because
where it is used for the increment alone then it is completely exchangeable
with the postfix form. Where it is used in a compound expression with the
value taken, it leads to confusion. The postfix form is useful for iterating
through arrays, whilst the prefix form is almost never so useful.

(This does lead us to the interesting issue of whether prefix --i should
also be banned. If you want to reverse through an array, generally you will
be passed the size of it, i.e. and index one past the end.)
Nov 14 '05 #27
ar**@post.com (asm) wrote in message news:<c8**************************@posting.google. com>...
Hi All,

I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.

The distinction is whether you need the current value of i (i++) or
the current value of i+1 (++i) in an expression.

Consider a simple stack implemented as an array. The stack grows from
element 0. We have a variable sp that always points to the last thing
pushed onto the stack. When we push a new value onto the stack, we
write to the next available array element and update sp to point to
this new element.

if (sp < STACK_SIZE)
{
/*
** The following statement replaces these two statements
**
** sp = sp + 1;
** stack[sp] = value;
*/
stack[++sp] = value;
}
else
{
/* handle overflow */
}

Popping or removing the top item from the stack is the inverse
operation; we return the value currently pointed to by sp, then
decrement by one:

if (sp > 0)
{
/*
** The following statement replaces these two statements
**
** value = stack[sp];
** sp = sp - 1;
*/
value = stack[sp--];
}
else
{
/* stack empty */
}
Does it really matter for assignments?

Yes.

i = 0;
j = i++; /* j == 0 */

i = 0;
j = ++i; /* j == 1 */
Thanks,
Arut

Nov 14 '05 #28

In article <ci**********@news6.svr.pol.co.uk>, "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:

In C, the form i++ is idiomatic. The form ++i really shouldn't be used. It
increments i before calculating the value of i, which is almost never
required.
Yet a quick scan through the 4062 C source files on this machine found
1068 instances of pre-increment and pre-decrement operators. Perhaps
idioms are different around these parts.

Obviously pre-increment are pre-decrement are never "required"; neither
are the post- forms, or the compound assignment operators, and so on.
Whether they're useful is a different question, as is whether they're
commonly used.
Even if it would be handy, its use will confuse maintaining
programmers.


(Conditional as subjunctive ... ugh. And then indicative as conditional.
What ill moods that sentence has.)

Few of those 1068 instances were written by me, yet I find none
of them confusing.

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

I'm not particularly funny, but I wanted to do something outrageous.
And I'm Norwegian, so I wasn't going to go too far. -- Darlyne Erickson
Nov 14 '05 #29
Malcolm <ma*****@55bank.freeserve.co.uk> wrote:
++i doesn't have such redeeming features. The form should be banned, because
where it is used for the increment alone then it is completely exchangeable
with the postfix form. Where it is used in a compound expression with the
value taken, it leads to confusion. The postfix form is useful for iterating
through arrays, whilst the prefix form is almost never so useful.


-----BEGIN SARCASM BLOCK-----
i++ should also be banned. It leads to confusion if you are not an expert
regarding C++, just take this example:
if (i++==i++) { ... }

Both arguments of the comparison are exactly the same. Nevertheless, the
comparison will return false. THIS IS GOING TO CONFUSE BEGINNERS! STRIP
POST-INCREMENTS FROM C++!!
------END SARCASM BLOCK------
--
Simon Stienen <http://dangerouscat.net> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle
Nov 14 '05 #30
Method Man wrote:
ProgrammerA might consider a 'for' loop easier to read than a 'while' loop,
whereas programmerB might think the opposite in the exact same code
semantics. So which way is more "boring and obvious"?
If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
With comma:
while(p++, *p) { ... }
Duplicating increment:
p++;
while(*p) { ...; p++; }

Even better is avoiding pointer arithmetic in the first place and
sticking to array indices:

int i;
for(i=1; p[i]; i++) { ... }

Induction variable elimination, now a commonplace optimization,
translates this into the original.
It just depends and my own programming experience in C/C++ has a lot to do with it.


I'm not saying pre/postincrement should be "banned" or that no one
should ever use them, but I do think not using them helps produce code
that most programmers can understand more easily. If I really wanted to
put force in this statement though I'd want a full usability study
behind it.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #31
Simon Stienen <si***********@news.slashlife.de> writes:
-----BEGIN SARCASM BLOCK-----
i++ should also be banned. It leads to confusion if you are not an expert
regarding C++, just take this example:
if (i++==i++) { ... }


If you *are* an expert, then this code tells you that its author
is an idiot and that you should avoid using it at all costs.
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #32
Ben Pfaff <bl*@cs.stanford.edu> wrote:
Simon Stienen <si***********@news.slashlife.de> writes:
-----BEGIN SARCASM BLOCK-----
i++ should also be banned. It leads to confusion if you are not an expert
regarding C++, just take this example:
if (i++==i++) { ... }


If you *are* an expert, then this code tells you that its author
is an idiot and that you should avoid using it at all costs.


Just needed some code to show Malcom that intuitive understandable code is
a matter of the code itself and therefore depends on the style of its
author - as soon as you have a minimum understanding on the C language...
Malcoms statement is like saying: "Since I am nearly unable to speak
French, French scientists are not allowed to use their special terms,
because I do not understand them if they do so!"
Every language, not limited to spoken languages, has terms, which somebody
who wants to learn this language has to learn, too. This is true even for
programming languages. If you don't learn your C vocabulary, obviously you
can't understand C code.

Malcom: Next time, you could demand XOR to be removed from the language
(and the microprocessors), because AND and OR are naturally unterstood
while XOR is far more complex an can be replaced with "(a OR b) AND NOT (a
AND b)" anstead of "a XOR b". :)
--
Simon Stienen <http://dangerouscat.net> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle
Nov 14 '05 #33

On Sat, 25 Sep 2004, Simon Stienen wrote:

Ben Pfaff <bl*@cs.stanford.edu> wrote:
Simon Stienen <si***********@news.slashlife.de> writes:
-----BEGIN SARCASM BLOCK-----
i++ should also be banned. It leads to confusion if you are not an expert
regarding C++, just take this example:
if (i++==i++) { ... }
If you *are* an expert, then this code tells you that its author
is an idiot and that you should avoid using it at all costs.


Just needed some code to show Malcom that intuitive understandable code is
a matter of the code itself and therefore depends on the style of its
author - as soon as you have a minimum understanding on the C language...


...you realize that the above snippet invokes undefined behavior and
thus can't be used to as an example in the way you suggested.
Malcoms statement is like saying: "Since I am nearly unable to speak
French, French scientists are not allowed to use their special terms,
because I do not understand them if they do so!"


To which you rejoined, "Je ne qxi pas frqustl maqnxwth!" :)

HTH,
-Arthur
Nov 14 '05 #34

"Michael Wojcik" <mw*****@newsguy.com> wrote

Yet a quick scan through the 4062 C source files on this machine found
1068 instances of pre-increment and pre-decrement operators. Perhaps
idioms are different around these parts.
As compared to how many post-increment / decrements?

Nov 14 '05 #35

"John Bode" <jo*******@my-deja.com> wrote

added by Malcolm

int stack[STACK_SIZE];
int sp;
if (sp < STACK_SIZE)
{
/*
** The following statement replaces these two statements
**
** sp = sp + 1;
** stack[sp] = value;
*/
stack[++sp] = value;
}
else
{
/* handle overflow */
}

Now I've added natural code given the identifiers you used. Since you only
posted a fragment, it isn't technically an error.
Your example shows UB when sp equals STACK_SIZE -1. As I said, use of
pre-increment can be confusing.

Nov 14 '05 #36
Malcolm <ma*****@55bank.freeserve.co.uk> wrote:
"Michael Wojcik" <mw*****@newsguy.com> wrote

Yet a quick scan through the 4062 C source files on this machine found
1068 instances of pre-increment and pre-decrement operators. Perhaps
idioms are different around these parts.

As compared to how many post-increment / decrements?


There are more people driving a pick-up than there are people driving a
caterpillar...
Let's stop producing caterpillars and use pick-ups instead.
--
Simon Stienen <http://dangerouscat.net> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle
Nov 14 '05 #37
Derrick Coetzee <dc****@moonflare.com> wrote in message news:<cj**********@news-int2.gatech.edu>...
asm wrote:
I would like to know when ++i should be used instead of i++ and vice versa.
Some code examples would be of help.


As a practical matter, you should almost never use either of these
except on a line by itself, in which case it doesn't matter. The
reasoning behind this claim is that it's difficult to read statements
using these operators and they can always be pulled out into a separate
statement. Here are some examples of pulling them out:

*p1++ = *p2++;
...becomes...
*p1 = *p2;
p1++; p2++;

while(*++p) { ... }
...becomes...
for(p++; *p; p++) { ... }

<snip>

I happen to disagree. This is purely a stylistic matter. It's
difficult for *you* to read, but more consise and more idiomatic in my
opinion.

We'll just have to agree to disagree.

Mark F. Haigh
mf*****@sbcglobal.net
Nov 14 '05 #38
On Sat, 25 Sep 2004 09:02:27 +0100, "Malcolm"
<ma*****@55bank.freeserve.co.uk> wrote:

"John Bode" <jo*******@my-deja.com> wrote

added by Malcolm

int stack[STACK_SIZE];
int sp;
if (sp < STACK_SIZE)
{
/*
** The following statement replaces these two statements
**
** sp = sp + 1;
** stack[sp] = value;
*/
stack[++sp] = value;
}
else
{
/* handle overflow */
}

Now I've added natural code given the identifiers you used. Since you only
posted a fragment, it isn't technically an error.
Your example shows UB when sp equals STACK_SIZE -1. As I said, use of
pre-increment can be confusing.


Yes, thank you, I tossed that off while waiting for a build to finish
and wasn't paying terribly close attention.
Nov 14 '05 #39
Derrick Coetzee wrote:

If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
[...]
Duplicating increment:
p++;
while(*p) { ...; p++; }


Note that these two forms are *not* necessarily
equivalent. For extra credit: Why not?

--
Er*********@sun.com

Nov 14 '05 #40
Derrick Coetzee <dc****@moonflare.com> wrote:
Method Man wrote:
It's all subjective to who the code's audience is. To experienced
programmers, operators like '++' become second nature.
Keep in mind that not every programmer who maintains your code may be an
expert, or be an expert who is particular lucid at the time (under high
stress, low on sleep, hangover, etc.)


If this "expert" is so very low on sleep that he isn't awake enough any
more to understand ++ and --, that expert has no business shoving his
grubby paws into _my_ code. Or anyone else's, for that matter. Let him
get a decent night's sleep and come back when he's capable of doing a
decent job again.
This is effectively a local transformation, unlike ++, which can potentially be
transmitted across an arbitrarily long string of tokens, as in this example:
_Transmitted_ across a string of tokens? Whatever do you mean by that?
b = a++ + /* one-million token expression */;


a gets increased. b gets the old value of a, plus that of the
million-token expression. What is there not to understand? What on
_earth_ is "transmitted" here?

Richard
Nov 14 '05 #41
Derrick Coetzee <dc****@moonflare.com> wrote:
Method Man wrote:
ProgrammerA might consider a 'for' loop easier to read than a 'while' loop,
whereas programmerB might think the opposite in the exact same code
semantics. So which way is more "boring and obvious"?


If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
With comma:
while(p++, *p) { ... }
Duplicating increment:
p++;
while(*p) { ...; p++; }


Congratulations. You've just turned a perfectly good, completely
understandable while loop into a rather more complicated and somewhat
less maintainable one, which may under unusual circumstances not even be
completely equivalent.

Richard
Nov 14 '05 #42

In article <cj**********@newsg4.svr.pol.co.uk>, "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:

The other baddy is the conditon ? x : y operator. It doesn't mean anything
to someone who doesn't know C (but is maybe a skilled programmer in another
language, and is forced to maintain your C program by circumstance),
Sure. And sometimes we have our plumber do carpentry work, so all of
our wooden framing members are soldered together.

A skilled programmer who is called on to maintain a program in an
unfamiliar language learns that language first. That's a necessary
condition of "skilled programmer".

Conversely, anyone who tries to maintain C code without understanding
the ternary operator is a fool. Trying to write non-trivial C code
that's proof against being maintained by fools is itself a fool's
errand.
++i doesn't have such redeeming features. The form should be banned, because
where it is used for the increment alone then it is completely exchangeable
with the postfix form. Where it is used in a compound expression with the
value taken, it leads to confusion.


Confusion for whom? You seem to be a member of a rather small
minority - just you, perhaps - which finds it confusing. Or do you
have some empirical data to demonstrate otherwise?

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

This is a "rubbering action game," a 2D platformer where you control a
girl equipped with an elastic rope with a fishing hook at the end.
-- review of _Umihara Kawase Shun_ for the Sony Playstation
Nov 14 '05 #43

In article <cj**********@newsg3.svr.pol.co.uk>, "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:

Your example shows UB when sp equals STACK_SIZE -1. As I said, use of
pre-increment can be confusing.
Non sequitur. The code displays the same UB without use of the
pre-increment operator (that is, if another increment expression,
such as the one John suggested in the comments, were substituted
for it), and nothing you've posted shows that the pre-increment
operator disguised that fact in any way.

Also, your argument hinges on your contention that stack be declared:
int stack[STACK_SIZE];
while it might just as easily have been declared:
int stack[STACK_SIZE+1];


The latter form - where a manifest constant for "array size" actually
refers to the largest valid index - is not uncommon in C source.
--
Michael Wojcik mi************@microfocus.com

Thanatos, thanatos! The labourer, dropping his lever,
Hides a black letter close to his heart and goes,
Thanatos, thanatos, home for the day and for ever. -- George Barker
Nov 14 '05 #44

In article <cj**********@newsg4.svr.pol.co.uk>, "Malcolm" <ma*****@55bank.freeserve.co.uk> writes:

"Michael Wojcik" <mw*****@newsguy.com> wrote

Yet a quick scan through the 4062 C source files on this machine found
1068 instances of pre-increment and pre-decrement operators. Perhaps
idioms are different around these parts.

As compared to how many post-increment / decrements?


An irrelevant query, since my claim was that the pre-increment and
pre-decrement operators are not, as you claimed, non-idiomatic; and
that they are in fact commonly used. I'd consider 1068 instances
pretty common.

But since you asked: 5028 instances of post-increment and -decrement.
That means the pre- forms represent about 18%, which certainly seems
to me sufficient to label them "common" and "idiomatic".

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

Today's Carnivore bait: Distracted by the Anthrax song, I let my bin,
laden with goods, crash into a bush.
Nov 14 '05 #45
In article <cj*********@news1.newsguy.com>,
Michael Wojcik <mw*****@newsguy.com> wrote:
Yet a quick scan through the 4062 C source files on this machine found
1068 instances of pre-increment and pre-decrement operators.


For stack-like applications, post-increment goes naturally with
pre-decrement and vice versa. Having used PDP-11 assembler a few
decades ago, I generally write i++ and --i when there is no other
reason to prefer one to the other.

-- Richard
Nov 14 '05 #46
On Mon, 27 Sep 2004, Eric Sosman wrote:
Derrick Coetzee wrote:

If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
[...]
Duplicating increment:
p++;
while(*p) { ...; p++; }


Note that these two forms are *not* necessarily
equivalent. For extra credit: Why not?


I'm not sure why these nits are allowed to continue; it all depends
on what ... is supposed to represent.

"float p=0"
Nov 14 '05 #47
Eric Sosman <er*********@sun.com> wrote:
Derrick Coetzee wrote:

If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
[...]
Duplicating increment:
p++;
while(*p) { ...; p++; }
Note that these two forms are *not* necessarily
equivalent. For extra credit: Why not?


Because "..." might contain "continue"?

--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05 #48
S.Tobias wrote:
Eric Sosman <er*********@sun.com> wrote:
Derrick Coetzee wrote:
If you prefer, here are some alternate translations:
Original:
while(*++p) { ... }
[...]
Duplicating increment:
p++;
while(*p) { ...; p++; }


Note that these two forms are *not* necessarily
equivalent. For extra credit: Why not?

Because "..." might contain "continue"?


Right you are! In the first form, `continue'
would transfer control to the test of `*++p', while
in the second it would go straight to testing `*p',
without incrementation.

--
Er*********@sun.com

Nov 14 '05 #49
Richard Bos wrote:
_Transmitted_ across a string of tokens? Whatever do you mean by that?


I refer to the distance the token would have to be moved in order for
the lexical order to reflect the execution order. The analogy wasn't
very good, since the same can happen with ->, but my point is that ++
and -- seriously screw with the correspondence between lexical order and
execution order.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #50

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

Similar topics

3
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.