473,811 Members | 2,911 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Blocks and Their Use

I have a question regarding *use* of blocks.

In Plauger's THE STANDARD C LIBRARY in xfmtval.c in Chapter 6 I noticed in
function _Fmtval() that after some processing of 50 lines or so he creates a
block

char *_Fmtval( ... )
{

/* .. 50 lines or so of code ... */

{ /* build string in buf under control of fmt */
char *end, *s;
const char *g;
size_t i, ns;

for (s = buf; *fmt; ++fmt, s+= strlen(s))
/* ... */

}
return (buf);

} /* end function _Fmtval */

We all know this is legitimate, but I admit I have not seen this technique
employed before. Plauger also uses this technique in setlocal.c in the same
chapter.

Is this technique recommended, or are there caveats? I can see some C Coding
Guidelines excluding its use, if not specifically then by implication,
perhaps.

Having just added some code to an existing file in a void function, I
elected to employ this techique. It takes the form:

if ( error )
{
/* report error */
return;
}

if ( another_error )
{
/* report this error */
return;
}

/* ... a few more error checks ... */

/* no errors here, start processing */
{
unsigned char c;
/* ... more definitions ... */

/*... processing ... */
}

Which I think works well because the variables defined in the block are
necessary only if the errors looked for above are not present.

Has anyone any constructive comments about this technique?

--
Martin

Mar 25 '07 #1
34 1513
"Martin" <martin.o_brien @[no-spam]which.netwrites :
I have a question regarding *use* of blocks.

In Plauger's THE STANDARD C LIBRARY in xfmtval.c in Chapter 6 I noticed in
function _Fmtval() that after some processing of 50 lines or so he creates a
block

char *_Fmtval( ... )
{

/* .. 50 lines or so of code ... */

{ /* build string in buf under control of fmt */
char *end, *s;
const char *g;
size_t i, ns;

for (s = buf; *fmt; ++fmt, s+= strlen(s))
/* ... */

}
return (buf);

} /* end function _Fmtval */

We all know this is legitimate, but I admit I have not seen this
technique employed before. Plauger also uses this technique in
setlocal.c in the same chapter.

Is this technique recommended, or are there caveats? I can see some
C Coding Guidelines excluding its use, if not specifically then by
implication, perhaps.
After reading the above, it wasn't at all clear to me what you meant
by "this technique". Reading the code after that that uses the
technique, I see that you're referring to introducing a block for the
purpose of declaring local variables that aren't needed by the
preceding code. (The subject "Blocks and Their Use" should have clued
me in!)

Yes, that's a perfectly valid technique, and I see nothing wrong with
it stylistically. Note that it doesn't necessarily save you any
memory; you might assume that the variables in the block won't be
allocated until and unless you enter the block, but that's not
guaranteed, and a compiler is free to allocate all of a function's
local variables (including ones in inner blocks) on entry to the
function. (Except for VLAs, I suppose.) But it does make it clear
that those variables are only used within the block, which makes the
code easier to understand.

Try moving the declarations of end, s, g, i, and ns to the beginning
of the function, above the "50 lines or so of code". Without
carefully reading all 50 lines, you can't be sure where those
variables are used.

I was about to express surprise that the code recomputes strlen(s) on
each iteration of the loop. It's a common newbie error to do
something like:

for (i = 0; i < strlen(s); i ++) {
/* ... code that uses s[i] ... */
}

The problem is that strlen() has to scan the entire string, making the
loop O(N**2). Saving the value of strlen(s) in a variable would make
it O(N), a significant improvement.

But of course P.J. Plauger didn't make such a newbie mistake.
strlen(s) *has* to be recomputed on each iteration, because it changes
on each iteration. The "s += strlen(s)" is simply a clever way to
advance the pointer s up to the next '\0' character.

--
Keith Thompson (The_Other_Keit h) 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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 25 '07 #2
Martin wrote:
I have a question regarding *use* of blocks.
<snip>
>
Having just added some code to an existing file in a void function, I
elected to employ this techique. It takes the form:

if ( error )
{
/* report error */
return;
}

if ( another_error )
{
/* report this error */
return;
}

/* ... a few more error checks ... */

/* no errors here, start processing */
{
unsigned char c;
/* ... more definitions ... */

/*... processing ... */
}

Which I think works well because the variables defined in the block are
necessary only if the errors looked for above are not present.

Has anyone any constructive comments about this technique?
It is a perfectly valid technique for containing the scope of variables.
It is also a strong hint that the code in the block might be better off
in its own function.

--
Ian Collins.
Mar 25 '07 #3
On Sun, 25 Mar 2007 21:15:59 +0100, "Martin"
<martin.o_brien @[no-spam]which.netwrote in comp.lang.c:
I have a question regarding *use* of blocks.

In Plauger's THE STANDARD C LIBRARY in xfmtval.c in Chapter 6 I noticed in
function _Fmtval() that after some processing of 50 lines or so he creates a
block

char *_Fmtval( ... )
{

/* .. 50 lines or so of code ... */

{ /* build string in buf under control of fmt */
char *end, *s;
const char *g;
size_t i, ns;

for (s = buf; *fmt; ++fmt, s+= strlen(s))
/* ... */

}
return (buf);

} /* end function _Fmtval */

We all know this is legitimate, but I admit I have not seen this technique
employed before. Plauger also uses this technique in setlocal.c in the same
chapter.

Is this technique recommended, or are there caveats? I can see some C Coding
Guidelines excluding its use, if not specifically then by implication,
perhaps.

Having just added some code to an existing file in a void function, I
elected to employ this techique. It takes the form:

if ( error )
{
/* report error */
return;
}

if ( another_error )
{
/* report this error */
return;
}

/* ... a few more error checks ... */

/* no errors here, start processing */
{
unsigned char c;
/* ... more definitions ... */

/*... processing ... */
}

Which I think works well because the variables defined in the block are
necessary only if the errors looked for above are not present.

Has anyone any constructive comments about this technique?
I use the technique of adding a block merely to open a local scope
most often when I am maintaining older code, my own or somebody
else's.

There is, unfortunately, a lot of older C code with very large
functions and all the variables used anywhere in the function defined
at the top.

In fact, I have seen C functions with dozens of cases in a switch
statement, all written in line, where some counter variable,
invariably named 'i', is used in two or three of the cases, and
defined way up at the top of the file.

The alternative is quite simply to put each case handler in its own
scope:

case '1':
{
/* define variables if needed */
break;
}

Opening a new scope allows you to make sure that you can define new
variables for added code in the middle of a function and helps you
avoid accidentally modifying the value of an existing on, especially
when it is not easy to see all the places where it might be used.

On the other hand, I never a block just to define a local scope in new
code. The code can always be structured better.

In your particular example, which could be a simplification, you could
open that block with an else or else if.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Mar 25 '07 #4
"Martin" <martin.o_brien @[no-spam]which.netwrote:

# Is this technique recommended, or are there caveats? I can see some C Coding
# Guidelines excluding its use, if not specifically then by implication,
# perhaps.

It's useful if you don't want to scan lots of code to make sure some
code you're inserting doesn't step on existing code.

Also useful if you have a real macro processor and you're building up
the code in diverse locations.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Leave it to the Catholics to destroy existence.
Mar 25 '07 #5

"Martin" <martin.o_brien @[no-spam]which.netwrote in message
[block scope variables] Which I think works well because the variables
defined in the block are necessary only if the errors looked for above are
not present.

Has anyone any constructive comments about this technique?
There is a limit to the number of scopes a programmer can cope with. We
already have global, file scope, and function scope variables. Adding
another scope would be too much, except that globals are typically used so
rarely that we can discount them. However when you have a hierarchy of
blocks each with different variables, the code can become unreadable.
I am against block scope variables because they encourage hacking rather
than thinking of the function as a unit, as well as on account of their
potential for introducing too many scopes. However I am not militantly
against them in short leaf blocks.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Mar 25 '07 #6

"SM Ryan" <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.orgw rote in
message
"Martin" <martin.o_brien @[no-spam]which.netwrote:

# Is this technique recommended, or are there caveats? I can see some C
Coding
# Guidelines excluding its use, if not specifically then by implication,
# perhaps.

It's useful if you don't want to scan lots of code to make sure some
code you're inserting doesn't step on existing code.
My point exactly.

Mar 25 '07 #7
In article <ea************ *********@bt.co m>,
>There is a limit to the number of scopes a programmer can cope with. We
already have global, file scope, and function scope variables. Adding
another scope would be too much, except that globals are typically used so
rarely that we can discount them. However when you have a hierarchy of
blocks each with different variables, the code can become unreadable.
I can't deny that you may find that the case, but examples from other
languages such as Lisp show that it's just a matter of opinion,
somewhat influenced by the syntax of the language in question.

I find that, for code of equal length, introducing sub-blocks often
improves readability by making the scope of variables explicit. On
the other hand, the amount of vertical whitespace it introduces in
most C styles works in the opposite direction.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Mar 26 '07 #8
On Sun, 25 Mar 2007 15:16:15 -0700, in comp.lang.c , Keith Thompson
<ks***@mib.orgw rote:
>you might assume that the variables in the block won't be
allocated until and unless you enter the block, but that's not
guaranteed, and a compiler is free to allocate all of a function's
local variables (including ones in inner blocks) on entry to the
function.
Really? Pathological case:

void foo()
{
double x = 4.5;
{
int x = 3;
}
{
char x[4]={"foo"};
}
}

Or is it a case of "it can, provided there are no side-effects"?

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 26 '07 #9
Mark McIntyre wrote:
On Sun, 25 Mar 2007 15:16:15 -0700, in comp.lang.c , Keith Thompson
<ks***@mib.orgw rote:

>>you might assume that the variables in the block won't be
allocated until and unless you enter the block, but that's not
guaranteed, and a compiler is free to allocate all of a function's
local variables (including ones in inner blocks) on entry to the
function.


Really? Pathological case:

void foo()
{
double x = 4.5;
{
int x = 3;
}
{
char x[4]={"foo"};
}
}

Or is it a case of "it can, provided there are no side-effects"?
The compiler is free to allocate the *storage* (typically space on the
stack). It could allocate space for sizeof(int)+4 bytes, or 4 bytes.

--
Ian Collins.
Mar 26 '07 #10

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

Similar topics

20
5945
by: Hung Jung Lu | last post by:
Hi, I know people have talked about it before, but I am still really confused from reading the old messages. When I talk about code blocks, I am not talking about Lisp/Ruby/Perl, so I am not making comparisons. If you have a file, in Python you could do:
2
374
by: BStorm | last post by:
I ran into a maddening bug that I finally tracked down to Microsoft's Data Access Blocks. It is in the SQL Helper UpdateDataSet method as follows: Microsoft Code: #region UpdateDataset public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName) { if( insertCommand == null ) throw new ArgumentNullException(
2
1269
by: Roshawn Dawson | last post by:
Hi, Does code contained in <% %> blocks cause postbacks to the server? Thanks, Roshawn
29
3684
by: John Rivers | last post by:
Hello, What good reason there is for not allowing methods in ASPX pages I can't imagine, but here is how to get around that limitation: (START) <body MS_POSITIONING="FlowLayout"> <form id="Form1" method="post" runat="server"> <%
14
2375
by: J.S. | last post by:
In a Windows Form application, which is the better method to concatenate large blocks of code? 1. Reading the text from text files. 2. Adding the text to the VB file itself? Thanks! J.S. --
3
2152
by: craig | last post by:
I was just wondering if anyone else may have incorporated the original Microsoft Exception Management Application Block (EMAB) or Data Access Application Block (DAAB) into one of their applications when the blocks were frist released several years ago? In the process of trying to upgrage an application to CLR 2.0, I thought it would make sense to also get the latest application blocks. The are now called the Enterprise Library...
2
1238
by: SparkPlug | last post by:
Given the following as true... 1. the importance of good software design & architecture, and learning good habits early on - even right at the beginning of a development career 2. the lack of easily accessible learning materials, tutorials, walk-throughs etc. for novices (I know there are some but not many) and the primarily-technical-in-nature Microsoft references for the Application Blocks (the UIPAB in my case)
26
2737
by: brenocon | last post by:
Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of locally-scoped-together code, in Ruby a "block" defines a closure (anonymous function). To avoid confusion let's call them Ruby block-closures. I see them as just a syntax for defining
3
1824
by: Andy B | last post by:
I need to search an xml element for blocks of text. The start of the text block will have a 5 digit number in it and i then need to read until the next 5 digit number. After this, I need to put them in different containers of their own. Where would I start?
0
9605
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10651
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5555
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5693
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3868
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.