473,666 Members | 2,634 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 2883
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
6716
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
5762
by: Yuk Cheng | last post by:
<<<start index.htm>>> <html> <head> <script> function perform(action){ } </script> </head>
39
2613
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
2705
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
2717
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
1682
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
4001
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
26624
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
5247
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
8438
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
8863
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
8779
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...
0
7376
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
5660
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
4186
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
4356
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2004
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1761
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.