for conditional handling question

A

Angus

Hello

My understanding is that the conditional expression in a for loop is
evaluated BEFORE each iteration. I understood this to mean that the
evaluation of a counter used would be BEFORE the counter is
incremented (or decremented or however changed).

But in my test code below:

for(; s < end; ++i)

this does not appear to be happening.

test code:
char start = 0;
char end = 0;
int i, j;
char s[27] = {0};

i=j=0;
start = 'A';
end = 'Z';

for(; s < end; ++i)
s = start + i;

I was expecting the char array s to be filled with A-Z and then stop.
ie in the test s < end, when s is Z (decimal 90) then end is
also Z (90) and so for loop should stop. But the for loop does NOT
stop.

If I try
for(; s[i-1] < end; ++i)
s = start + i;

Then the for loop does end at the correct point so I am assuming that
i is incremented before the test. Can someone please confirm what is
the expected behaviour.

Angus
 
J

jacob navia

Le 02/01/11 10:47, Angus a écrit :
Hello

My understanding is that the conditional expression in a for loop is
evaluated BEFORE each iteration. I understood this to mean that the
evaluation of a counter used would be BEFORE the counter is
incremented (or decremented or however changed).

But in my test code below:

for(; s< end; ++i)

this does not appear to be happening.


You test for s < 'Z'. Since s contains 27
zeroes, it will be ALWAYS smaller than 'Z'. You go beyond
the bounds of the array.
 
W

Willem

Angus wrote:
) Hello
)
) My understanding is that the conditional expression in a for loop is
) evaluated BEFORE each iteration. I understood this to mean that the
) evaluation of a counter used would be BEFORE the counter is
) incremented (or decremented or however changed).

The evaluation of all the code inside the loop body
is also done BEFORE the counter is incremented.

for (S; C; I) { X; Y; }

is done in this order:
S; C; X; Y; I; C; X; Y; I; ... X; Y; I; C;
(The last C is false, all the others are true)

With that in mind, try to think about what your code is doing.

) test code:
) char start = 0;
) char end = 0;
) int i, j;
) char s[27] = {0};
)
) i=j=0;
) start = 'A';
) end = 'Z';
)
) for(; s < end; ++i)
) s = start + i;
....
) Then the for loop does end at the correct point so I am assuming that
) i is incremented before the test. Can someone please confirm what is
) the expected behaviour.

If you connect the ends of a loop, then the end of the loop comes right
before the start of the loop. The increment, which is at the end, is
directly followed by the conditional, which is at the start.

So yes, this is the expected behaviour.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 
N

Nick Keighley

My understanding is that the conditional expression in a for loop is
evaluated BEFORE each iteration.
yes

 I understood this to mean that the
evaluation of a counter used would be BEFORE the counter is
incremented (or decremented or however changed).

no

this:-
for (i = begin(); i = inc(i); is_end(i))
proc();

is roughly equivalent to:-
i = begin();
again:
if (is_end(i))
goto exit;
proc();
i = inc(i);
goto again;
exit:

But in my test code below:

for(; s < end; ++i)

this does not appear to be happening.

test code:
        char start = 0;
        char end = 0;
        int i, j;
        char s[27] = {0};

        i=j=0;
        start = 'A';
        end = 'Z';

        for(; s < end; ++i)
                s = start + i;

I was expecting the char array s to be filled with A-Z and then stop.
ie in the test s < end, when s is Z (decimal 90) then end is
also Z (90) and so for loop should stop.  But the for loop does NOT
stop.

If I try
        for(; s[i-1] < end; ++i)
                s = start + i;

Then the for loop does end at the correct point so I am assuming that
i is incremented before the test.  Can someone please confirm what is
the expected behaviour.

Angus
 
N

Nick Keighley

Why not just code what you meant instead of writing for Obfusticated C?

    int c, i; for (c='A', i=0; c<'Z'; c++, i++) s = c;


this assumes ASCII or someother code where the letters are contiguous
and in order
 
E

Eric Sosman

Hello

My understanding is that the conditional expression in a for loop is
evaluated BEFORE each iteration.

Yes.
I understood this to mean that the
evaluation of a counter used would be BEFORE the counter is
incremented (or decremented or however changed).

I'm not sure what this means. The middle expression in a `for'
is just an expression, evaluating whatever it evaluates and producing
whatever side-effects it produces.
But in my test code below:

for(; s< end; ++i)

this does not appear to be happening.

test code:
char start = 0;
char end = 0;
int i, j;
char s[27] = {0};

i=j=0;
start = 'A';
end = 'Z';

for(; s< end; ++i)
s = start + i;

I was expecting the char array s to be filled with A-Z and then stop.
ie in the test s< end, when s is Z (decimal 90) then end is
also Z (90) and so for loop should stop. But the for loop does NOT
stop.


There's nothing to stop it. Consider the first iteration: for's
middle expression finds `i' is 0, `s[0]' is 0, and that is less than
`end' (the values of all the "standard" characters are strictly
positive. So the loop body executes and deposits 'A' in `s[0]'.
Then the third expression executes, setting `i' to 1. Back to the
middle expression: `i' is 1, `s[1]' is 0, that's less than `end', and
the loop body executes again (the precise effect this time depends on
the character coding; it is not a given that 'A'+1 == 'B'). Then the
third expression sets `i' to 2, the middle expression finds `s[2]' is
zero, and the loop proceeds merrily along.

After the `i=26' iteration things get strange. The third expression
sets `i' to 27, and then the middle expression executes. Since it tries
to inspect the non-existent `s[27]' there's really no telling what might
happen. Most probably -- but not for certain -- the loop will plow
forward through the memory locations that happen to follow `s', and
may eventually stop if it encounters one that happens to hold a value
greater than 'Z', meanwhile scribbling over whatever else it finds
along the way. Maybe it will scribble on something important, maybe
not. Maybe it will scribble on `end' or on `i' and make the behavior
very erratic. Maybe it will crash.
If I try
for(; s[i-1]< end; ++i)
s = start + i;


This is also bad: On the very first test, when `i' is 0, it
tries to inspect the non-existent `s[-1]'. Lord only knows what
it might find there.
Then the for loop does end at the correct point so I am assuming that
i is incremented before the test. Can someone please confirm what is
the expected behaviour.

The statement `for (e1; e2; e3) { body }' is almost equivalent to

{
e1;
while (e2) {
{ body }
e3;
}
}

(The "almost" covers two cases: If `e2' is missing entirely `while(e2)'
is treated as `while(1)', and if "body" executes a `continue', the
for-loop proceeds to `e3' while the while-loop would not. But if `e2'
is non-empty and there's no `continue', the equivalence holds.)

In other words, a "for" statement does:

1: If `e1' is present, evaluate it. (And bring into existence
any variables it happens to declare These variables live
as long as the loop is executing, and cease to exist when
it terminates for any reason.)

2: If `e2' is present, evaluate it. If it evaluates to zero,
terminate the "for" and skip to whatever follows the body.

3: Execute the body. If the body doesn't end the loop (for
example, with `break' or `return' or some such), then ...

4: ... if `e3' is present, evaluate it.

5: Go back to step [2], with all variables holding whatever
the body and/or `e3' put in them.
 
B

BartC

test code:
char start = 0;
char end = 0;
int i, j;
char s[27] = {0};

i=j=0;
start = 'A';
end = 'Z';

for(; s < end; ++i)
s = start + i;

I was expecting the char array s to be filled with A-Z and then stop.
ie in the test s < end, when s is Z (decimal 90) then end is
also Z (90) and so for loop should stop. But the for loop does NOT
stop.

If I try
for(; s[i-1] < end; ++i)
s = start + i;


Those tests look a bit dodgy. If you have to start to think about exactly
how these things work, then perhaps you need a simply way of setting up this
array. For example:

int i,start,end;
char s['Z'-'A'+2]={0};

start='A';
end='Z';

for (i=start; i<=end; ++i) s[i-start]=i;

puts(s);

if you need to use a loop. (Simplest is just char s[]="ABC...Z";)
 
E

Eric Sosman

Nick Keighley said:
Why not just code what you meant instead of writing for Obfusticated C?

int c, i; for (c='A', i=0; c<'Z'; c++, i++) s = c;


this assumes ASCII or someother code where the letters are contiguous
and in order


The original post had consecutive letters.


The original post had consecutive *character codes*. They started
with the letter 'A', but beyond that the code-character correspondence
was uncertain.
 
B

BartC

Eric Sosman said:
In
article<995a71f8-af73-4780-be5e-0f80e4f1854d@n10g2000yqd.googlegroups.com>,
Nick Keighley said:
Why not just code what you meant instead of writing for Obfusticated C?

int c, i; for (c='A', i=0; c<'Z'; c++, i++) s = c;

this assumes ASCII or someother code where the letters are contiguous
and in order


The original post had consecutive letters.


The original post had consecutive *character codes*. They started
with the letter 'A', but beyond that the code-character correspondence
was uncertain.


If you had to place a bet, with the same odds both ways, as to whether the
letters were consecutive or not, which would it be? How much money would you
put on it?

(And ignore the fact the OP mentioned that 'Z' had code 90...)
 
B

Ben Bacarisse

Nick Keighley said:
no

this:-
for (i = begin(); i = inc(i); is_end(i))
proc();

I think you intended to write:

for (i = begin(); is_end(i); i = inc(i))
proc();
is roughly equivalent to:-
i = begin();
again:
if (is_end(i))

You need !is_end(i) here. Maybe you tripped yourself up by using the
wrong name: is_end is not a good name for a function that returns true
when the loop is to continue!
goto exit;
proc();
i = inc(i);
goto again;
exit:

<snip>
 
E

Eric Sosman

Eric Sosman said:
In
article<995a71f8-af73-4780-be5e-0f80e4f1854d@n10g2000yqd.googlegroups.com>,




Why not just code what you meant instead of writing for
Obfusticated C?

int c, i; for (c='A', i=0; c<'Z'; c++, i++) s = c;

this assumes ASCII or someother code where the letters are contiguous
and in order

The original post had consecutive letters.


The original post had consecutive *character codes*. They started
with the letter 'A', but beyond that the code-character correspondence
was uncertain.


If you had to place a bet, with the same odds both ways, as to whether
the letters were consecutive or not, which would it be? How much money
would you put on it?


I'll bet all the money I can scrape together *against* consecutive
codes for letters. With my winnings, I'll travel the world and visit
all the great opera houses, hearing Aïda, Götterdämmerung, Borís
Godunóv (БориÑÑŠ Годуновъ), Thaïs, Die Entführung aus dem Serail ...
(And ignore the fact the OP mentioned that 'Z' had code 90...)

In light of the O.P.'s code, do you consider him authoritative
on matters computational? (He may become so someday, but at present
his grasp of computer programming appears to me a bit infirm.)
 
N

Nick Keighley

I think you intended to write:

       for (i = begin(); is_end(i); i = inc(i))
           proc();


You need !is_end(i) here.  Maybe you tripped yourself up by using the
wrong name: is_end is not a good name for a function that returns true
when the loop is to continue!

am I having a bad day? I intended the program to jump to the exit if
is_end() was true... I choose the names to look a bit like STL
iterators
 
B

Ben Bacarisse

Nick Keighley said:
am I having a bad day? I intended the program to jump to the exit if
is_end() was true... I choose the names to look a bit like STL
iterators

And so it does, but what, then, is the equivalent 'for' loop? What you
originally posted:

for (i = begin(); i = inc(i); is_end(i))

can't be right and it looked like a simple typo so I suggested a
correction, but that correction might not have been what you intended.

If you do indeed want the loop to exit when is_end is true
then you should have stared off with:

for (i = begin(); !is_end(i); i = inc(i))

but that looks like an odd choice when explaining a 'for' loop. I would
not illustrate the general meaning of a loop by picking one with a
negated condition (though of course it makes no logical difference to
experienced programmers).

<snip>
 
S

Seebs

My understanding is that the conditional expression in a for loop is
evaluated BEFORE each iteration. I understood this to mean that the
evaluation of a counter used would be BEFORE the counter is
incremented (or decremented or however changed).

You are confused.

for (i = 0; i < 3; ++i) {
printf("%d\n", i);
}

will print:
0
1
2

The key to understanding this is that "++i" is the *END* of an iteration.
Thus, "before" each iteration means "before the body of the loop is
executed". However, the increment will then occur before the *next*
test.
char start = 0;
char end = 0;
int i, j;
char s[27] = {0};

i=j=0;
start = 'A';
end = 'Z';

for(; s < end; ++i)
s = start + i;


This won't work, because s is a different character when you test
than it was when you assigned to it.
Then the for loop does end at the correct point so I am assuming that
i is incremented before the test. Can someone please confirm what is
the expected behaviour.

Yes, this is.

Think it through! If we take your reading, then each iteration of the loop
body would occur with a different value than the condition tested for. Thus,
the standard idiom for looping over a linked list wouldn't work:

for (p = head; p != NULL; p = p->next)

This would, under your model, verify that the last member of the list
wasn't a null pointer, then set p to the null pointer at the end of the
list and execute the loop body with that untested value.

The third clause of a for loop happens after the loop body but before
the *next* test.

-s
 
A

Angus

Why not just code what you meant instead of writing for Obfusticated C?

    int c, i; for (c='A', i=0; c<'Z'; c++, i++) s = c;

or just

    memcpy(s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 26);

--
Damn the living - It's a lovely life.           I'm whoever you want me to be.
Silver silverware - Where is the love?       At least I can stay in character.
Oval swimming pool - Where is the love?    Annoying Usenet one post at a time.
Damn the living - It's a lovely life.         You like me! You really like me!



Yes but this is not the real program. Caller will specify a start and
end character.
 
A

Angus

Angus wrote:

) Hello
)
) My understanding is that the conditional expression in a for loop is
) evaluated BEFORE each iteration.  I understood this to mean that the
) evaluation of a counter used would be BEFORE the counter is
) incremented (or decremented or however changed).

The evaluation of all the code inside the loop body
is also done BEFORE the counter is incremented.

  for (S; C; I) { X; Y; }

is done in this order:
  S; C; X; Y; I; C; X; Y; I; ... X; Y; I; C;
(The last C is false, all the others are true)

With that in mind, try to think about what your code is doing.

) test code:
)       char start = 0;
)       char end = 0;
)       int i, j;
)       char s[27] = {0};
)
)       i=j=0;
)       start = 'A';
)       end = 'Z';
)
)       for(; s < end; ++i)
)               s = start + i;
...
) Then the for loop does end at the correct point so I am assuming that
) i is incremented before the test.  Can someone please confirm what is
) the expected behaviour.

If you connect the ends of a loop, then the end of the loop comes right
before the start of the loop.  The increment, which is at the end, is
directly followed by the conditional, which is at the start.

So yes, this is the expected behaviour.

SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
            made in the above text. For all I know I might be
            drugged or something..
            No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT


Thanks that explains the behaviour well. I will re-write the loop.
 
S

sandeep

Eric said:
In other words, a "for" statement does:

1: If `e1' is present, evaluate it. (And bring into existence
any variables it happens to declare These variables live as long as
the loop is executing, and cease to exist when it terminates for any
reason.)

2: If `e2' is present, evaluate it. If it evaluates to zero,
terminate the "for" and skip to whatever follows the body.

I believe it is more correct to say that e1 and e2 are evaluated whether-
or-not they are empty. It just happens that evaluating an empty
expression has no effect and yields a TRUE value.
 
W

Willem

sandeep wrote:
) Eric Sosman writes:
)> In other words, a "for" statement does:
)>
)> 1: If `e1' is present, evaluate it. (And bring into existence
)> any variables it happens to declare These variables live as
) long as
)> the loop is executing, and cease to exist when it terminates
) for any
)> reason.)
)>
)> 2: If `e2' is present, evaluate it. If it evaluates to zero,
)> terminate the "for" and skip to whatever follows the body.
)
) I believe it is more correct to say that e1 and e2 are evaluated whether-
) or-not they are empty. It just happens that evaluating an empty
) expression has no effect and yields a TRUE value.

You believe wrongly. As an example:

if () { /* something */ }

The ability to not have expressions is quite specific to for-loops.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 
N

Nick Keighley

And so it does, but what, then, is the equivalent 'for' loop?  What you
originally posted:

    for (i = begin(); i = inc(i); is_end(i))

can't be right and it looked like a simple typo so I suggested a
correction, but that correction might not have been what you intended.

I had the for loop wrong in the first place :-(
If you do indeed want the loop to exit when is_end is true
then you should have stared off with:

    for (i = begin(); !is_end(i); i = inc(i))

*that* is what I meant!
but that looks like an odd choice when explaining a 'for' loop.  I would
not illustrate the general meaning of a loop by picking one with a
negated condition (though of course it makes no logical difference to
experienced programmers).

I perhaps over generalised. Since begin and end were functions I
decided the inc should be as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top