String reversing problem

T

tmp123

To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.
The second comments, about sequence points, well, I must recognize I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.

To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.

Kind regards.
 
T

Tim Rentsch

tmp123 said:
To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.

The problem is that the variable 'e' is decremented even if it is
equal to the address held in 's'. That means the decrement can
attempt to set 'e' to an address "before" the first element of
the array object holding the string, which is disallowed. It's
allowed to point to one element past the end of an array object,
but not allowed to point to one element before the beginning.
 
C

Christian Bau

"tmp123 said:
To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.
The second comments, about sequence points, well, I must recognize I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.

To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.

Nothing wrong with my english. Lots wrong with your code. I don't care
too much about the undefined behavior, because you managed to write
completely incomprehensible code for a very simple task.

void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;

while (i < j)
{
char tmp = s ;
s = s [j];
s [j] = tmp;
++i;
--j;
}
}

works and is easy to understand.
 
T

tmp123

Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer (it is
only assigned, not used, and probably the final address will be valid).


However, if you say that standard allows to pass the end of the array
but not point before, I can accept the reasoning.

Kind regards.
 
M

Mark McIntyre

I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.

©ISO/IEC ISO/IEC 9899:1999 (E)
Annex C
(informative)
Sequence points
1 The following are the sequence points described in 5.1.2.3:
— The call to a function, after the arguments have been evaluated
(6.5.2.2).
— The end of the first operand of the following operators: logical AND
&& (6.5.13);
logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).
— The end of a full declarator: declarators (6.7.5);
— The end of a full expression: an initializer (6.7.8); the expression
in an expression
statement (6.8.3); the controlling expression of a selection statement
(if or switch)
(6.8.4); the controlling expression of a while or do statement
(6.8.5); each of the
expressions of a for statement (6.8.5.3); the expression in a return
statement
(6.8.6.4).
— Immediately before a library function returns (7.1.4).
— After the actions associated with each formatted input/output
function conversion
specifier (7.19.6, 7.24.2).
— Immediately before and immediately after each call to a comparison
function, and
also between any call to a comparison function and any movement of the
objects
passed as arguments to that call (7.20.5).

(Of Christian's comment)
Your English seems not to be the most valid to be used in net,

Grow a thicker skin.

Personally I also thought the code was an abhomination and had I
discovered it in a project I was running I'd have told the programmer
to remove it forthwith.

Mark McIntyre
 
M

Mark McIntyre

Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer

Thats not relevant. If it breaks the rules of the C standard, then its
not guaranteed to work, and you should not do it. One day your code
will be run on an OS which does care, and you will be fired / lose
money / lose face or whatever because of your code error.

Mark McIntyre
 
T

Tim Rentsch

tmp123 said:
Thanks for the explanation.

You're welcome, glad it was of help.

I do not know any compiler nor OS with problems for this pointer (it is
only assigned, not used, and probably the final address will be valid).

In most practical cases it won't be a problem. However, the Standard
is quite unambiguous that it is potentially a problem, and there are
some implementations (I'm pretty sure) where it fails.

However, if you say that standard allows to pass the end of the array
but not point before, I can accept the reasoning.

One way to learn about these things is to get a copy of the
Standard, and read it yourself. There's an updated version
you can get just by downloading:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf

If you get a copy then you can read up on sequence points or
whatever else (including array indexing and pointer arithmetic)
and many of the comments on comp.lang.c will make a lot more
sense.

Kind regards.

Likewise. And Happy New Year.
 
R

Richard Heathfield

tmp123 said:
Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer

The backroom boys are working on one right now, for all you know. And it
might just be tomorrow's sensational new toy for other, unrelated reasons.
And your boss might just say, "let's migrate all our code to this new
thing", as bosses often do. And at that point, the guys who stuck to the
rules will have working code, and the guys who didn't, won't.

So it pays to do things properly.
 
T

tmp123

Hi,

See inlines:

Christian said:
Nothing wrong with my english. Lots wrong with your code. I don't care
too much about the undefined behavior, because you managed to write
completely incomprehensible code for a very simple task.

Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.

And taken into account that this piece of code has been presented as
"the good one" in a real programming team, some comments about:
void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;

1) It is not the same initialize a variable as give a variable the
first value it will take.
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.
while (i < j)

4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initializations,
exit condition and state update).
{
char tmp = s ;


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).
s = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.
++i;
--j;

7) Lost lines here?
}
}

works and is easy to understand.

8) "Works" is not a measure of quality.

This is my last post in this subject. I don not like to be troll, nor
feed trolls.

Kind regards.
 
S

slebetman

tmp123 said:
Hi,

See inlines:



Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.

"For fun" still doesn't make your code correct. You stated that it
works but the experts here have pointed out that even so it is still
not correct "C". So that doesn't invalidate Mark's comments - your code
still is horrible, learn and move on.

As for your comment about Mark's tone being aggressive, you have to
learn that this is Usenet, and taking on an aggressive tone is a
tradition of the net long before you showed up. Some groups liks
comp.lang.tcl may be less aggressive but comp.lang.c is aggressive (I
learned that the hard way). Maybe it's because so many people keep
asking the same stupid questions here over and over again (and keep
making the same stupid mistakes that others have made before).
1) It is not the same initialize a variable as give a variable the
first value it will take.

What are you trying to say here? That code is correct.
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).

I don't see how this is different from your code since you yourself
introduce the variable 'r'.
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.

Lost? I understood it. The code is short and clear so it is
stylistically correct to use simple variable names (n, x, y, i, j
etc..). For that matter, the "relation between" 'r' and 's' in your
code and "their meaning/usage" also fall into the same category.
4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initializations,
exit condition and state update).

"Easy to read"? Certainly not your code. And in Mark's code "while" is
quite natural - use the right tool for the right job.
{
char tmp = s ;


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".
s = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Nope, the above fragment of code will compile on any C compiler, I
suspect it is even valid in the original K&R "C" but I'm not sure.
8) "Works" is not a measure of quality.

True, as the experts here have pointed out about YOUR code. But "easy
to understand" IS a measure of quality.
This is my last post in this subject. I don not like to be troll, nor
feed trolls.

Mark have not been acting like a troll. He was merely scolding you for
writing poor code. You however are increasingly acting in a troll like
manner by insisting to argue even when you've been proven wrong.
 
S

slebetman

tmp123 said:
Hi,

See inlines:



Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.

"For fun" still doesn't make your code correct. You stated that it
works but the experts here have pointed out that even so it is still
not correct "C". So that doesn't invalidate Mark's comments - your code
still is horrible, learn and move on.

As for your comment about Mark's tone being aggressive, you have to
learn that this is Usenet, and taking on an aggressive tone is a
tradition of the net long before you showed up. Some groups liks
comp.lang.tcl may be less aggressive but comp.lang.c is aggressive (I
learned that the hard way). Maybe it's because so many people keep
asking the same stupid questions here over and over again (and keep
making the same stupid mistakes that others have made before).
1) It is not the same initialize a variable as give a variable the
first value it will take.

What are you trying to say here? That code is correct.
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).

I don't see how this is different from your code since you yourself
introduce the variable 'r'.
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.

Lost? I understood it. The code is short and clear so it is
stylistically correct to use simple variable names (n, x, y, i, j
etc..). For that matter, the "relation between" 'r' and 's' in your
code and "their meaning/usage" also fall into the same category.
4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initializations,
exit condition and state update).

"Easy to read"? Certainly not your code. And in Mark's code "while" is
quite natural - use the right tool for the right job.
{
char tmp = s ;


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".
s = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Nope, the above fragment of code will compile on any C compiler, I
suspect it is even valid in the original K&R "C" but I'm not sure.
8) "Works" is not a measure of quality.

True, as the experts here have pointed out about YOUR code. But "easy
to understand" IS a measure of quality.
This is my last post in this subject. I don not like to be troll, nor
feed trolls.

Mark have not been acting like a troll. He was merely scolding you for
writing poor code. You however are increasingly acting in a troll like
manner by insisting to argue even when you've been proven wrong.


Oh crap, I thought tmp123 was referring to Mark. I meant Christian.
Sorry for the identity mix-up. My comments still stand though.
 
F

Flash Gordon

tmp123 said:
Hi,

See inlines:



Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.

If it is a learning exercise, then you should appreciate the advice not
dismiss it because it is only a learning exercise.
And taken into account that this piece of code has been presented as
"the good one" in a real programming team, some comments about:


1) It is not the same initialize a variable as give a variable the
first value it will take.

What you are saying makes no sense. Initialising a variable *is* giving
it the first value it will take!
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).

What has that got to do with writing the code properly first time?
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.

i and j are conventionally used as loop iterators. You will just have to
get used to it if you are going to read other peoples code.
4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initializations,
exit condition and state update).

I'm sure he has, but there is nothing intrinsically wrong with what
Christian Bau has done. In a case like this I'm in two minds about
whether to do it the way he has done it or using a for loop and not
initialising the variables on declaration since I can see arguments both
ways.
{
char tmp = s ;


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


It is called localising scope and is often considered a good thing.
Whether or not the compiler generates a new stack frame (which is
unlikely) is irrelevant.
s = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Compilers have been doing this king of optimisation for over 10 years,
so I hardly think a modern compiler is required.
7) Lost lines here?

What lost lines? I see nothing missing.
8) "Works" is not a measure of quality.

So you consider a program that does not work to be of the same quality
as one that does work? That is just plain stupid. His code is of far
higher quality by all measures I would use than your code is.
This is my last post in this subject. I don not like to be troll, nor
feed trolls.

Well, Christian Bau is not a troll. He posted a good example of how to
implement the function in order to assist you. If you cannot see that
then that is your problem.
 
F

Flash Gordon

tmp123 said:
Hi,

See inlines:
{
char tmp = s ;

5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".


Actually, you declaring a variable at the start of any block is valid
for all versions of C. Also, there are I believe a few complete C99
implementations, just not many.
s = s [j];
s [j] = tmp;

6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Nope, the above fragment of code will compile on any C compiler, I
suspect it is even valid in the original K&R "C" but I'm not sure.


It is valid for all versions.
True, as the experts here have pointed out about YOUR code. But "easy
to understand" IS a measure of quality.

<snip>

Whether code works is definitely one of the measures of quality, just
not the only one. If code does not work it is poor quality even if it is
easy to read. For example, here is a very low quality, but easy to read,
implementation of a program to copy standard input to standard output.
#include <stdio.h>
int main(FILE *standard_input, FILE *standard_output)
{
standard_output = standard_input;
}

Nice and simple, easy to read, compiles under gcc (with -ansi -pedantic)
without warning or error, but probably one of the lowest quality
programs I've ever seen. I could also do ones that are (by some measure)
just as low quality but do not invoke undefined behaviour.
 
E

Emmanuel Delahaye

Albert a écrit :
void reverse(char s[], int num_elements)
{
int i, j;

for (i=0,j=num_elements-1; (i<=num_elements-1) && (j>=0); i++,j--)
s = s[j];
}


You need a swap action, hence a local variable.
 
S

slebetman

Flash said:
tmp123 said:
Hi,

See inlines:

Christian Bau wrote:
tmp123 wrote:
To Mr. Christian Bau:
{
char tmp = s ;
5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".


Actually, you declaring a variable at the start of any block is valid
for all versions of C.


Oh wow, tested it and it does work. I've always thought that "start of
block" refers to the start of the function. Learn something new
everyday. This is indeed nice as localising scope is usually a "good
thing"(tm).
 
M

Mark McIntyre

1) It is not the same initialize a variable as give a variable the
first value it will take.

Thats highly garbled, but I' guessing you're complaining that
initialising is not the same as assigning a value. So what?
2) Not always a stack to add variables is available,

irrelevant since your own example also introduced variables
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.

Rubbish. And your own version had the same mysterious loop variables.
If you object to that, call them start and end or somthing.
4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initializations,
exit condition and state update).

You're objecting to a while loop ? You're either a knave or a fool.
{
char tmp = s ;


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things.


No, its a way to simplify the code.
And lots of compilers will ignore it (no new frame).

Absolute rubbish.
s = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Rubbish. This is perfectly correct C, and always has been.
7) Lost lines here?

No, it seems you simply don't understand the function.
8) "Works" is not a measure of quality.

Its one measure. If it doesn't work, then its useless rubbish code,
no?
This is my last post in this subject. I don not like to be troll,

Then stop behaving like one.

Happy New Year by the way.
Mark McIntyre
 
N

Netocrat

On Sat, 31 Dec 2005 12:26:04 +0000, Flash Gordon wrote:
[a refutation of tmp123's objections to a reverse_string() implementation]

I agree with most of your response, but I want to take up a couple of
points. Most of tmp123's legitimate objections related to style, except
for his indexing comment. Reading between the lines, his objections seem
to result in a rewriting of the function to something like this:

void reverse_string_mod(char* s)
{
char tmp, *ps, *pe;

if (*s != '\0')
{
for (ps = s, pe = s + strlen (s) - 1; ps < pe; ps++, pe--) {
tmp = *ps;
*ps = *pe;
*pe = tmp;
}
}
}


Where Christian Bau's original function was:

void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;

while (i < j)
{
char tmp = s ;
s = s [j];
s [j] = tmp;
++i;
--j;
}
}

Due to the need for the zero-length test, there is no reduction in
vertical space - this possibility is what I believe tmp123 was implying
could be achieved when he wrote "Lost lines here?" (it was an obscure
wording though and I may have misinterpreted it).
In a case like this I'm in two minds about whether to do it the way he
[Christian Bau] has done it or using a for loop and not initialising the
variables on declaration since I can see arguments both ways.

Likewise; although the reduction in vertical space and the clustering of
all looping information in one spot seem good reasons to prefer the for
loop style.

Vertical space is something I've come to be conservative about in C code,
since I find that - all other things equal, and with the qualification
that occasional empty lines for semantic demarcation are useful - the less
vertical scrolling/eye-movement required, the faster I can take in the
code's meaning. For this reason I prefer a bracing style that doesn't
place starting braces on a new line, and that avoids braces where it's
possible to do so without otherwise reducing readability.

[re a claim that indexing requires the compiler to optimise compared to
pointer arithmetic]
Compilers have been doing this king of optimisation for over 10 years,
so I hardly think a modern compiler is required.

The equivalent pointer-arithmetic code is both a well-accepted idiom and
optimal at an abstract level (at abstract level the additional indexing
calculations are always performed), and for those reasons I find it
preferable.

The optimisations of modern compilers are often unpredictable - doing some
checking using gcc and icc on my machine, I find that the
pointer-arithmetic version is /generally/ slightly faster across
optimisation levels and string lengths, but not always.

For comment, a vertically-minimalist re-writing of the pointer-arithmetic
version of the function:

void reverse_string_min_vert(char *s) {
char tmp, *ps, *pe;

if (*s != '\0')
for (ps = s, pe = s + strlen(s) - 1; ps < pe; ps++, pe--)
tmp = *ps, *ps = *pe, *pe = tmp;
}

Pros: very little vertical eye movement required; one line per high-level
operation (test for non-zero length, loop over the string, swap a
character on each iteration)
Cons: wide horizontal spacing; a lot of code to digest on each line; the
omitted braces may reduce the code's readability for those who are used to
mandatory braces.

Would this pass review at your shop? Why/why not?
 
F

Flash Gordon

Netocrat said:
On Sat, 31 Dec 2005 12:26:04 +0000, Flash Gordon wrote:
[a refutation of tmp123's objections to a reverse_string() implementation]

Due to the need for the zero-length test, there is no reduction in
vertical space - this possibility is what I believe tmp123 was implying
could be achieved when he wrote "Lost lines here?" (it was an obscure
wording though and I may have misinterpreted it).

Very obscure if that is what it meant..
As you (Flash Gordon) wrote:

[re a claim that indexing requires the compiler to optimise compared to
pointer arithmetic]
Compilers have been doing this king of optimisation for over 10 years,
so I hardly think a modern compiler is required.

The equivalent pointer-arithmetic code is both a well-accepted idiom and
optimal at an abstract level (at abstract level the additional indexing
calculations are always performed), and for those reasons I find it
preferable.

The optimisations of modern compilers are often unpredictable - doing some
checking using gcc and icc on my machine, I find that the
pointer-arithmetic version is /generally/ slightly faster across
optimisation levels and string lengths, but not always.

Yes, but:
1) It is only the highest optimisation levels (one for speed and one for
space) that count IMHO, and you've not specified if there is any
difference at that point.
2) Readability and maintainability are far more important.

For this, I might have used either indexing or pointers, and would be
unlikely to comment on the choice made at a review.
For comment, a vertically-minimalist re-writing of the pointer-arithmetic
version of the function:

void reverse_string_min_vert(char *s) {
char tmp, *ps, *pe;

if (*s != '\0')
for (ps = s, pe = s + strlen(s) - 1; ps < pe; ps++, pe--)
tmp = *ps, *ps = *pe, *pe = tmp;
}

Pros: very little vertical eye movement required; one line per high-level
operation (test for non-zero length, loop over the string, swap a
character on each iteration)
Cons: wide horizontal spacing; a lot of code to digest on each line; the
omitted braces may reduce the code's readability for those who are used to
mandatory braces.

Would this pass review at your shop? Why/why not?

I would not reject it out of hand but for me there is too much occurring
on each line and therefore takes me longer to read.
 
T

tmp123

{
char tmp = s ;
5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).

This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".


Actually, you declaring a variable at the start of any block is valid
for all versions of C.


Oh wow, tested it and it does work. I've always thought that "start of
block" refers to the start of the function. Learn something new
everyday. This is indeed nice as localising scope is usually a "good
thing"(tm).



"works" only "more or less". Imagine you have a function with two big
locals.The first one is used at the start of function, the second one
at the end. You can thing this version saves stack space:

void test ( void )
{
{
char tmp1[10000];
... some code
}
{
char tmp2[10000];
... more code
}
}

However, if you display the address of tmp1 and tmp2, you will see that
lots of compilers converts it to:
void test ( void )
{
char tmp1[10000];
char tmp2[10000];
... some code
... more code
}

that is not the expected one. That doesn't means this resource must not
be used. But it is good to known what will happen.

Kind regards.
 
S

slebetman

tmp123 said:
{
char tmp = s ;
5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).

This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".

Actually, you declaring a variable at the start of any block is valid
for all versions of C.


Oh wow, tested it and it does work. I've always thought that "start of
block" refers to the start of the function. Learn something new
everyday. This is indeed nice as localising scope is usually a "good
thing"(tm).



"works" only "more or less". Imagine you have a function with two big
locals.The first one is used at the start of function, the second one
at the end. You can thing this version saves stack space:

void test ( void )
{
{
char tmp1[10000];
... some code
}
{
char tmp2[10000];
... more code
}
}

However, if you display the address of tmp1 and tmp2, you will see that
lots of compilers converts it to:
void test ( void )
{
char tmp1[10000];
char tmp2[10000];
... some code
... more code
}


At the assembly level maybe but at the "C" level not true. Try
compiling:

#include <stdio.h>
int main()
{
int i;
for (i=0;i<10;i++) {
int n = i * 2;
printf("%d\n", n);
}
n = 3;
printf("%d\n", n);
}

and you'll get:

testprog.c: In function `main':
testprog.c:14: error: `n' undeclared (first use in this function)
testprog.c:14: error: (Each undeclared identifier is reported only once
testprog.c:14: error: for each function it appears in.)

Localising scope has little to do with trying to save memory but have
more to do with protecting variables from being misused. Think of the
difference of local and global, only in this case we get to use
variables that are more 'local' than local (if you know what I mean).

The first language I encountered this feature is in Perl. Little did I
know that C had it all along.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top