473,895 Members | 3,071 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Effect of goto on local variables

I am in a situation where only "goto" seems to be the answer for my
program logic where I have to retry calling some repeated functions.

Can anybody help in the usage of goto and its effect in local
variables, as shown in the stripped code below
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
.....
.....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

.....
.....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine
Nov 13 '05 #1
8 2912
pertheli wrote:
I am in a situation where only "goto" seems to be the answer for my
program logic where I have to retry calling some repeated functions.

Can anybody help in the usage of goto and its effect in local
variables, as shown in the stripped code below
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine


Why don't you allocate memory before the loop?

Then you could write:

void Process()
{
int iRetryCount, iMaxRetry = 100;
char *myVar1 = malloc(100); /* Error-checking perhaps? */

for (iRetryCount=0; iRetryCount<iMa xRetry; ++iRetryCount)
{
somefunction1() ;
if ( somefunction2() ) break;
}
}

Or you could use a while loop based on condition somefunction2()
with the break inside the body, or use both tests inside the while
loop. I don't think this is an example where goto is unavoidable.

BTW, you can't declare bNewBool in the middle of your code in C.

Nov 13 '05 #2
In message <48************ **************@ posting.google. com>
pe******@hotmai l.com (pertheli) wrote:
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine


Ignoring any issues of style, taste, decency etc, when the goto itself
happens, bNewBool and myVar1 will retain their value. When their declarations
are reached again, they will be reinitialised, and a new block of 100 will be
allocated for myVar1. Thus your code as written is basically valid (as C99 or
C++).

For what it's worth, "if (myVar1) free(myVar1);" can be simplified to
"free(myVar1);" , as free() is required to accept a NULL pointer and do
nothing

--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1223 503458
Cambridge, CB5 8HE, United Kingdom WWW: http://www.tematic.com/
Nov 13 '05 #3


pertheli wrote:
I am in a situation where only "goto" seems to be the answer for my
program logic where I have to retry calling some repeated functions.
I've heard some people suggest that explicit loops can sometimes be used
instead of the much more obvious backward gotos ;-).
Can anybody help in the usage of goto and its effect in local
variables, as shown in the stripped code below
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}

<snip>

Wouldn't this be clearer:

void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
.....
.....
while (iRetryCount < iMaxRetry) {
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
free(myVar1);
}

.....
.....
}

I assume that you want to free(myVar1) even if you're not going to
retry, so my code above also fixes that bug. I also assume that you'll
have some code after the malloc to test for myVar1 being NULL and you
don't need to test for that before free-ing it anyway.

Ed.

Nov 13 '05 #4

"Kevin Bracey" <ke**********@t ematic.com> wrote in message
news:31******** ********@temati c.com...
In message <48************ **************@ posting.google. com>
pe******@hotmai l.com (pertheli) wrote:
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine
Ignoring any issues of style, taste, decency etc, when the goto itself
happens, bNewBool and myVar1 will retain their value. When their

declarations are reached again, they will be reinitialised, and a new block of 100 will be allocated for myVar1. Actually, that is technically incorrect. The goto leaves the scope of the
bNewBool and myVar1 variables, and so the values those variables had are
forgotten. Then, after the goto, the code reenters the scope of the
bNewbool and myVar1 variables, which are then initialized in this case.

The distinction doesn't matter with the OP's code, but does in the following
case:

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

In this case, the variable value is uninitialized when the program hits the
printf, resulting in Undefined Behavior.
Thus your code as written is basically valid (as C99 or
C++).

That it is (after replacing the .... sections with valid code, of course)

--
poncho
Nov 13 '05 #5
In message <rC************ *******@newsrea d1.news.pas.ear thlink.net>
"Scott Fluhrer" <sf******@ix.ne tcom.com> wrote:

"Kevin Bracey" <ke**********@t ematic.com> wrote in message
news:31******** ********@temati c.com...
In message <48************ **************@ posting.google. com>
pe******@hotmai l.com (pertheli) wrote:
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine


Ignoring any issues of style, taste, decency etc, when the goto itself
happens, bNewBool and myVar1 will retain their value. When their
declarations are reached again, they will be reinitialised, and a new
block of 100 will be allocated for myVar1.


Actually, that is technically incorrect. The goto leaves the scope of the
bNewBool and myVar1 variables, and so the values those variables had are
forgotten.


No, that's not so. At least, assuming we're talking about C99; the issue
doesn't arise in C90, and I wouldn't know about C++ (although I'd be
surprised if it was fundementally different from C99).

There is a difference between scope and storage duration. See the heinous
example in section 6.2.4 of the C99 rationale. In the OP's example, the
goto leaves the scope of bNewBool and myVar1, but execution hasn't left
their associated block, so they still exist and retain their contents (and
could be accessed via a pointer).

--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1223 503458
Cambridge, CB5 8HE, United Kingdom WWW: http://www.tematic.com/
Nov 13 '05 #6
pertheli wrote:

I am in a situation where only "goto" seems to be the answer for my
program logic where I have to retry calling some repeated functions.

Can anybody help in the usage of goto and its effect in local
variables, as shown in the stripped code below

void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}
....
}

What is the effect of calling repeated "Retry:" block to the local
variables such as bNewBool, myVar1, myVar2? Are they called again? ie
reinitialised? Is it safe to use? although it seems to be working fine


Reworked to be legitimate C and eliminate the goto. I believe the
action is identical.

Since you are using // comments you must have a C99 compiler.
However to use bool you must include stdbool.h, and to use
malloc/free you must include stdlib.h.

#include <stdbool.h>
#include <stdlib.h>
....
void Process() {
int iMaxRetry = 100;
int iRetryCount = 0;
bool bNewBool;
char *myVar1;
.....
do {
iRetryCount++;
somefunction1() ;
bNewBool = false;
myVar1 = malloc(100);
if (!somefunction2 ()) {
if (iRetryCount < iMaxRetry) {
bNewBool = true;
free(myVar1);
}
}
} while (bNewBool);
.....
}

I suggest you dispense with the silly hungarian notation. You
could probably easily wrap further actions withing somefunction2
and simplify further. Then that loop would look like:

do {
tries++
somefunction1(& MyVar1));
} while (somefunction2( tries, MyVar1));

and not strain the credulity of the average reader :-)

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #7
On Tue, 2 Dec 2003 11:43:27 UTC, pe******@hotmai l.com (pertheli)
wrote:
I am in a situation where only "goto" seems to be the answer for my
program logic where I have to retry calling some repeated functions.

Can anybody help in the usage of goto and its effect in local
variables, as shown in the stripped code below
void Process(){

int iMaxRetry = 100;
int iRetryCount = 0;
....
....
Retry:
iRetryCount++; // counter for retrying
somefunction1() ;
bool bNewBool = false; // some local variable
char* myVar1 = malloc(100);
if (!somefunction2 ()){ // if condition is not valid retry
if (iRetryCount < iMaxRetry){
if (myVar1) free(myVar1);
goto Retry; // go back and try again
}
}

....
....
}


/* count backwards because test for 0 is more efficient than compare 2
variables */
/* use postdecrement because it saves some typing */
for (iRetrycount = iMaxRetry; iRetryCount--; ) {
/* C89 requires all declarations done befor the first statement
gets called */
bool bNewBool = FALSE;
char *myVar1 = malloc(100);
if (!myvar) continue; /* as original code tells somefuctionx needs
myvar set */
somefuction1();
if (somefunction2( )) break; /* somefuction2 says 'done' */
free(myVar); /* free does nothing when called with NULL pointer
*/
}

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.pc-rosenau.de

Nov 13 '05 #8
The Real OS/2 Guy wrote:

/* count backwards because test for 0 is more efficient than compare 2
variables */
/* use postdecrement because it saves some typing */
for (iRetrycount = iMaxRetry; iRetryCount--; ) {


Oh, good grief! One could equally well argue that counting
forward is better because clearing the counter to zero is "more
efficient" than initializing it to a non-zero value. Without
some idea of how many times the loop will be executed, it's not
possible to say which effect will dominate.

And either way, the savings -- if any -- will be trivial,
as in too small to measure.

A friend of mine used to refer to this sort of optimization
as "Cleaning the bottle caps off the beach so the sand will be
nice and smooth around the whale carcasses."

--
Er*********@sun .com
Nov 13 '05 #9

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

Similar topics

8
431
by: pertheli | last post by:
I am in a situation where only "goto" seems to be the answer for my program logic where I have to retry calling some repeated functions. Can anybody help in the usage of goto and its effect in local variables, as shown in the stripped code below void MyClass:Process(){ int iMaxRetry = 100;
36
6761
by: Michael | last post by:
Hi, I know I know its notoriously bad! I don't want to use it. I was wondering, does it still exist? If it does, I really don't understand how!? like what happens if you just goto halfway through a function (no objects properly constructed!) , or a constructor itself?? Just intrigued!! Mike
4
5793
by: Yuk Cheng | last post by:
<<<start index.htm>>> <html> <head> <script> function perform(action){ } </script> </head>
39
2652
by: vineoff | last post by:
If I'm having nested loops like: for (...) for (..) for (...) { /* exit here */ } and I need to exit from there ^ . Is it better to use exceptions or goto or some other method?
45
2742
by: Debashish Chakravarty | last post by:
K&R pg.66 describes two situations when using goto makes sense. Has anyone here come across situations where using goto provided the most elegant solution. -- http://www.kashmiri-pandit.org/atrocities/index.html
28
2744
by: Vishal Naidu | last post by:
i m new to the C world... i ve been told by my instructors not to use goto stmt.. but no one could give me a satisfactory answer as to why it is so.. plz help me out of this dilemma, coz i use a lot of goto in my codes....
5
1701
by: cody | last post by:
I have a very funny/strange effect here. if I let the delegate do "return prop.GetGetMethod().Invoke(info.AudioHeader, null);" then I get wrong results, that is, a wrong method is called and I have no clue why. But if I store the MethodInfo in a local variable I works as expected. I do not understand why this is so, shouldn't both ways be semantically equal?
77
4067
by: M.B | last post by:
Guys, Need some of your opinion on an oft beaten track We have an option of using "goto" in C language, but most testbooks (even K&R) advice against use of it. My personal experience was that goto sometimes makes program some more cleaner and easy to understand and also quite useful (in error handling cases). So why goto is outlawed from civilized c programmers community. is there any technical inefficiency in that.
34
26676
by: electrician | last post by:
Perl has it, Basic has it, Fortran has it. What is so difficult about creating a goto command for JavaScript. Just set up a label and say go to it.
3
5272
by: Beamer | last post by:
Hi I am trying to build a roating slide effect in javascript. Basically, I have a list like below <ul id="slideShowCnt"> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li>
0
9988
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9833
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
11247
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
10841
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10931
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
8025
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6066
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4684
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3293
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.