T
tmp123
Hi,
See inlines
Kind regards.
Thanks for showing the difference between variable scope, visibility,
life... . It can be interesting for some readers.
See this function:
/* swap pairs of characters in strings: 12345 => 21435 */
void reverse ( char *s )
{
/* end condition */
if ( s[0]=='\0' || s[1]=='\0' ) return;
/* swap values */
{
char tmp;
tmp=s[0];
s[0]=s[1];
s[1]=tmp;
}
reverse(s+2);
}
There are older languages than perl with it.
Kind regards.
See inlines
Kind regards.
tmp123 said: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.)
Thanks for showing the difference between variable scope, visibility,
life... . It can be interesting for some readers.
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).
See this function:
/* swap pairs of characters in strings: 12345 => 21435 */
void reverse ( char *s )
{
/* end condition */
if ( s[0]=='\0' || s[1]=='\0' ) return;
/* swap values */
{
char tmp;
tmp=s[0];
s[0]=s[1];
s[1]=tmp;
}
reverse(s+2);
}
The first language I encountered this feature is in Perl. Little did I
know that C had it all along.
There are older languages than perl with it.
Kind regards.