Why use do { ... } while (FALSE); in C++ outside of macros [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Are do-while-false loops common?
Is there a reason to have code like:
do {
// a lot of code that only needs to be run once
} while (FALSE);
when the code isn't defining a macro? I know it's a trick when it comes to macros, but is there a reason for it in normal code?

Well, it does allow you to use the break; (or continue) keyword for early exit if you have a need for that for some reason. That would be kinda ugly though. I'd really rather see it moved into its own routine, with the early exit implemented via a return; statement.

Well one reason for it would be if you want to break out at some point.
i.e.
do
{
//some code that should always execute...
if ( condition )
{
//do some stuff
break;
}
//some code that should execute if condition is not true
if ( condition2 )
{
//do some more stuff
break;
}
//further code that should not execute if condition or condition2 are true
}
while(false);
In certain situations the resulting code is a little bit more clear / easier to understand if written as above.

Such a construct is used as a kind of goto to be able to jump after the end of the loop using a break statement inside.

I would not do this but:
I looks slightly more logical than just braces
int main()
{
{
std::ifstream file("Data");
// DO STUFF
} // Data now closed.
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}
An unobservant maintainer may see the braces and think.
What the heck and remove them
int main()
{
std::ifstream file("Data");
// DO STUFF
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// FAIL. data is still open from before.
std::ofstream file2("Data");
// DO STUFF
}
I suppose using the while tick at least make syou think about it (though an unobservant maintainer may still remove it).
int main()
{
do
{
std::ifstream file("Data");
// DO STUFF
} while (false);
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}

There is no reason to ever write a loop that is known, at compile time, to execute exactly once.
Doing so, in order to pretend that goto is written as break, is abusive.
EDIT:
I've just realised that my assertion about compile-time knowledge is false: I suppose you might do something complicated with conditional #defines that might mean that, at compile time for one build configuration, it is known to execute once, but for a different build configuration, it is executed multiple times.
#ifdef SOMETHING
#define CONDITION (--x)
#else
#define CONDITION 0
#endif
...
int x = 5
do{
...
} while(CONDITION)
However, the spirit of my assertion still stands.

It can be used to implement a behavior similar to goto statement, or say jump behavior!
See this:
do
{
if (doSomething() != 0) break; //jump
if (doSomethingElse() != 0) break; //jump
...
if (doSomethingElseNew() != 0) break; //jump
} while(false);
//if any of the break encountered, execution can continue from here, just after the do-while block!
// statement1
// statement2
// statement3
// so on
Taken from here: Are do-while-false loops common?

Related

Use of goto in this very specific case... alternatives?

I have a question about the possibile use of goto in a C++ code: I know that goto shall be avoided as much as possibile, but in this very particular case I'm having few difficulties to find good alternatives that avoid using multiple nested if-else and/or additional binary flags...
The code is like the following one (only the relevant parts are reported):
// ... do initializations, variable declarations, etc...
while(some_flag) {
some_flag=false;
if(some_other_condition) {
// ... do few operations (20 lines of code)
return_flag=foo(input_args); // Function that can find an error, returning false
if(!return_flag) {
// Print error
break; // jump out of the main while loop
}
// ... do other more complex operations
}
index=0;
while(index<=SOME_VALUE) {
// ... do few operations (about 10 lines of code)
return_flag=foo(input_args); // Function that can find an error, returning false
if(!return_flag) {
goto end_here; // <- 'goto' statement
}
// ... do other more complex operations (including some if-else and the possibility to set some_flag to true or leave it to false
// ... get a "value" to be compared with a saved one in order to decide whether to continue looping or not
if(value<savedValue) {
// Do other operations (about 20 lines of code)
some_flag=true;
}
// ... handle 'index'
it++; // Increse number of iterations
}
// ... when going out from the while loop, some other operations must be done, at the moment no matter the value of some_flag
return_flag=foo(input_args);
if(!return_flag) {
goto end_here; // <- 'goto' statement
}
// ... other operations here
// ... get a "value" to be compared with a saved one in order to decide whether to continue looping or not
if(value<savedValue) {
// Do other operations (about 20 lines of code)
some_flag=true;
}
// Additional termination constraint
if(it>MAX_ITERATIONS) {
some_flag=false;
}
end_here:
// The code after end_here checks for some_flag, and executes some operations that must always be done,
// no matter if we arrive here due to 'goto' or due to normal execution.
}
}
// ...
Every time foo() returns false, no more operations should be executed, and the code should execute the final operations as soon as possible. Another requirement is that this code, mainly the part inside the while(index<=SOME_VALUE) shall run as fast as possible to try to have a good overall performance.
Is using a 'try/catch' block, with the try{} including lots of code inside (while, actually, the function foo() can generate errors only when called, that is in two distinct points of the code only) a possibile alternative? Is is better in this case to use different 'try/catch' blocks?
Are there other better alternatives?
Thanks a lot in advance!
Three obvious choices:
Stick with goto
Associate the cleanup code with the destructor of some RAII class. (You can probably write it as the delete for a std::unique_ptr as a lambda.)
Rename your function as foo_internal, and change it to just return. Then write the cleanup in a new foo function which calls foo_internal
So:
return_t foo(Args...) {
const auto result = foo_internal(Args..);
// cleanup
return result;
}
In general, your function looks too long, and needs decomposing into smaller bits.
One way you can do it is to use another dummy loop and break like so
int state = FAIL_STATE;
do {
if(!operation()) {
break;
}
if(!other_operation()) {
break;
}
// ...
state = OK_STATE;
} while(false);
// check for state here and do necessary cleanups
That way you can avoid deep nesting levels in your code beforehand.
It's C++! Use exceptions for non-local jumps:
try {
if(some_result() < threshold) throw false;
}
catch(bool) {
handleErrors();
}
// Here follows mandatory cleanup for both sucsesses and failures

Preprocessor Directive for Repeated Code Blocks (with condition)

Is there any way in C++ to implement a concept like the following pseudo-code?
#pragma REPEAT
for (;;)
{
// code block #1
#pragma REPEAT_CONDITION(a==1)
// code
#end_pragma
// code block #2
}
#end_pragma
Which would get compiled as something like this:
if (a == 1)
{
for (;;)
{
// code block #1
// code
// code block #2
}
}
else
{
for (;;)
{
// code block #1
// code block #2
}
}
The goal here being to generate an easily readable piece of performance code by abstracting a condition from the inner loop. Thus not having to manually maintain duplicated code blocks.
Honestly, the preprocessor should be used for conditional compilation and precious little else nowadays. With inline(-suggesting) functions, insanely optimising compilers and enumerations, their most common use cases have been gradually whittled away.
I'm assuming here you don't want to check the condition every time through the loop, even though this cleans up your code considerably:
for (;;) {
// code block #1
if (a == 1) {
// code
}
// code block #2
}
The only reason I could think of you doing this would be for the extra speed of not doing the check multiple times but you may want to actually check the impact it has. Unless // code is pitifully simple, it will most likely swamp the effect of a single conditional statement.
If you do need the separate loops for whatever reason, you may be better off putting those common code blocks into functions and simply calling them with a one-liner:
if (a == 1) {
for (;;) {
callCodeBlock1();
// code
callCodeBlock2();
} else {
for (;;) {
callCodeBlock1();
callCodeBlock2();
}
}

Weirdest C++ stack empty() fault

My program crashes because it reaches a stack.top() it shouldn't reach, as the stack is empty.
I have an if which checks just that:
if(!st.empty());
//do stuff
(I have initialized
stack<int> st;
).
But although I can see in the debug that the stack is empty, it still goes in the if!
I even wrote this code:
if(st.size()>0);
cout<<st.size();
And it prints 0!
What is going on and how can I fix it? Thanks!
The semicolons after the if statements are the problem
BAD:
if(st.size()>0); // <-- this should not be here!!!!!!!!
cout<<st.size();
Properly rewritten:
if(st.size()>0) {
cout<<st.size();
}
Also, as #WhozCraig pointed out, the other statement has a semicolon too!
BAD:
if(!st.empty()); // <--BAD!
//do stuff
Good:
if(!st.empty()) {
//do stuff
}
ALWAYS!! use brackets with branches (if, switch), and loops (for, while, do-while)!!! It pays off big time! (Not to mention, a cute kitten dies each and every time such a block is written without brackets!) ALWAYS!!
For example this can kill a day in debugging:
BAD:
int i=0;
...
while(i++<1000);
doStuff(i);
Good:
int i=0;
...
while(i++<1000) {
doStuff(i);
}
Beware (as #WhozCraig pointed out again) this does not automagically solve the problem of semicolon terminated branch and loop statements, as this is perfectly valid syntax:
if (condition);{ ...code... }
Or
if (condition);
{
...code...
}
But in my opinion and experience (this is totally subjective!) - as I myself have fallen into this trap a couple of times - I experienced that when I have the curly bracket after the aforementioned statements, I didn't ever make the mistake of typing a semicolon again. Adhering to this convention was a silver bullet - for me, and others could benefit from this too. Also, if there was a semicolon there, it would immediately catch my eye, just by looking, as it is an "uncommon pattern of characters".
There is no "in the if", as your if contains only an empty statement:
if(!st.empty());
//do stuff -- that's outside the if!!!!
(Background: The syntax is if (condition) block, with block being either a statement or a block of statements. ; is an empty statement, so if (...) ; means "if condition fulfilled then do nothing" -- which probably never is what you have in mind.)
You should write
if(!st.empty()) {
//do stuff -- now it's inside!
}
Be careful! Do NOT write
if(!st.empty()); // notice the semicolon making it wrong; without the semicolon it would be ok
{
// outside again
}

Use of goto for cleanly exiting a loop

I have a question about use of the goto statement in C++. I understand that this topic is controversial, and am not interested in any sweeping advice or arguments (I usually stray from using goto). Rather, I have a specific situation and want to understand whether my solution, which makes use of the goto statement, is a good one or not. I would not call myself new to C++, but would not classify myself as a professional-level programmer either. The part of the code which has generated my question spins in an infinite loop once started. The general flow of the thread in pseudocode is as follows:
void ControlLoop::main_loop()
{
InitializeAndCheckHardware(pHardware) //pHardware is a pointer given from outside
//The main loop
while (m_bIsRunning)
{
simulated_time += time_increment; //this will probably be += 0.001 seconds
ReadSensorData();
if (data_is_bad) {
m_bIsRunning = false;
goto loop_end;
}
ApplyFilterToData();
ComputeControllerOutput();
SendOutputToHardware();
ProcessPendingEvents();
while ( GetWallClockTime() < simulated_time ) {}
if ( end_condition_is_satisified ) m_bIsRunning = false;
}
loop_end:
DeInitializeHardware(pHardware);
}
The pHardware pointer is passed in from outside the ControlLoop object and has a polymorphic type, so it doesn't make much sense for me to make use of RAII and to create and destruct the hardware interface itself inside main_loop. I suppose I could have pHardware create a temporary object representing a sort of "session" or "use" of the hardware which could be automatically cleaned up at exit of main_loop, but I'm not sure whether that idea would make it clearer to somebody else what my intent is. There will only ever be three ways out of the loop: the first is if bad data is read from the external hardware; the second is if ProcessPendingEvents() indicates a user-initiated abort, which simply causes m_bIsRunning to become false; and the last is if the end-condition is satisfied at the bottom of the loop. I should maybe also note that main_loop could be started and finished multiple times over the life of the ControlLoop object, so it should exit cleanly with m_bIsRunning = false afterwards.
Also, I realize that I could use the break keyword here, but most of these pseudocode function calls inside main_loop are not really encapsulated as functions, simply because they would need to either have many arguments or they would all need access to member variables. Both of these cases would be more confusing, in my opinion, than simply leaving main_loop as a longer function, and because of the length of the big while loop, a statement like goto loop_end seems to read clearer to me.
Now for the question: Would this solution make you uncomfortable if you were to write it in your own code? It does feel a little wrong to me, but then I've never made use of the goto statement before in C++ code -- hence my request for help from experts. Are there any other basic ideas which I am missing that would make this code clearer?
Thanks.
Avoiding the use of goto is a pretty solid thing to do in object oriented development in general.
In your case, why not just use break to exit the loop?
while (true)
{
if (condition_is_met)
{
// cleanup
break;
}
}
As for your question: your use of goto would make me uncomfortable. The only reason that break is less readable is your admittance to not being a strong C++ developer. To any seasoned developer of a C-like language, break will both read better, as well as provide a cleaner solution than goto.
In particular, I simply do not agree that
if (something)
{
goto loop_end;
}
is more readable than
if (something)
{
break;
}
which literally says the same thing with built-in syntax.
With your one, singular condition which causes the loop to break early I would simply use a break. No need for a goto that's what break is for.
However, if any of those function calls can throw an exception or if you end up needing multiple breaks I would prefer an RAII style container, this is the exact sort of thing destructors are for. You always perform the call to DeInitializeHardware, so...
// todo: add error checking if needed
class HardwareWrapper {
public:
HardwareWrapper(Hardware *pH)
: _pHardware(pH) {
InitializeAndCheckHardware(_pHardware);
}
~HardwareWrapper() {
DeInitializeHardware(_pHardware);
}
const Hardware *getHardware() const {
return _pHardware;
}
const Hardware *operator->() const {
return _pHardware;
}
const Hardware& operator*() const {
return *_pHardware;
}
private:
Hardware *_pHardware;
// if you don't want to allow copies...
HardwareWrapper(const HardwareWrapper &other);
HardwareWrapper& operator=(const HardwareWrapper &other);
}
// ...
void ControlLoop::main_loop()
{
HardwareWrapper hw(pHardware);
// code
}
Now, no matter what happens, you will always call DeInitializeHardware when that function returns.
UPDATE
If your main concern is the while loop is too long, then you should aim at make it shorter, C++ is an OO language and OO is for split things to small pieces and component, even in general non-OO language we generally still think we should break a method/loop into small one and make it short easy for read. If a loop has 300 lines in it, no matter break/goto doesn't really save your time there isn't it?
UPDATE
I'm not against goto but I won't use it here as you do, I prefer just use break, generally to a developer that he saw a break there he know it means goto to the end of the while, and with that m_bIsRunning = false he can easily aware of that it's actually exit the loop within seconds. Yes a goto may save the time for seconds to understand it but it may also make people feel nervous about your code.
The thing I can imagine that I'm using a goto would be to exit a two level loop:
while(running)
{
...
while(runnning2)
{
if(bad_data)
{
goto loop_end;
}
}
...
}
loop_end:
Instead of using goto, you should use break; to escape loops.
There are several alternative to goto: break, continue and return depending on the situation.
However, you need to keep in mind that both break and continue are limited in that they only affect the most inner loop. return on the other hand is not affected by this limitation.
In general, if you use a goto to exit a particular scope, then you can refactor using another function and a return statement instead. It is likely that it will make the code easier to read as a bonus:
// Original
void foo() {
DoSetup();
while (...) {
for (;;) {
if () {
goto X;
}
}
}
label X: DoTearDown();
}
// Refactored
void foo_in() {
while (...) {
for (;;) {
if () {
return;
}
}
}
}
void foo() {
DoSetup();
foo_in();
DoTearDown();
}
Note: if your function body cannot fit comfortably on your screen, you are doing it wrong.
Goto is not good practice for exiting from loop when break is an option.
Also, in complex routines, it is good to have only one exit logic (with cleaning up) placed at the end. Goto is sometimes used to jump to the return logic.
Example from QEMU vmdk block driver:
static int vmdk_open(BlockDriverState *bs, int flags)
{
int ret;
BDRVVmdkState *s = bs->opaque;
if (vmdk_open_sparse(bs, bs->file, flags) == 0) {
s->desc_offset = 0x200;
} else {
ret = vmdk_open_desc_file(bs, flags, 0);
if (ret) {
goto fail;
}
}
/* try to open parent images, if exist */
ret = vmdk_parent_open(bs);
if (ret) {
goto fail;
}
s->parent_cid = vmdk_read_cid(bs, 1);
qemu_co_mutex_init(&s->lock);
/* Disable migration when VMDK images are used */
error_set(&s->migration_blocker,
QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
"vmdk", bs->device_name, "live migration");
migrate_add_blocker(s->migration_blocker);
return 0;
fail:
vmdk_free_extents(bs);
return ret;
}
I'm seeing loads of people suggesting break instead of goto. But break is no "better" (or "worse") than goto.
The inquisition against goto effectively started with Dijkstra's "Go To Considered Harmful" paper back in 1968, when spaghetti code was the rule and things like block-structured if and while statements were still considered cutting-edge. ALGOL 60 had them, but it was essentially a research language used by academics (cf. ML today); Fortran, one of the dominant languages at the time, would not get them for another 9 years!
The main points in Dijkstra's paper are:
Humans are good at spatial reasoning, and block-structured programs capitalise on that because program actions that occur near each other in time are described near each other in "space" (program code);
If you avoid goto in all its various forms, then it's possible to know things about the possible states of variables at each lexical position in the program. In particular, at the end of a while loop, you know that that loop's condition must be false. This is useful for debugging. (Dijkstra doesn't quite say this, but you can infer it.)
break, just like goto (and early returns, and exceptions...), reduces (1) and eliminates (2). Of course, using break often lets you avoid writing convoluted logic for the while condition, getting you a net gain in understandability -- and exactly the same applies for goto.

Examples of good gotos in C or C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 9 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In this thread, we look at examples of good uses of goto in C or C++. It's inspired by an answer which people voted up because they thought I was joking.
Summary (label changed from original to make intent even clearer):
infinite_loop:
// code goes here
goto infinite_loop;
Why it's better than the alternatives:
It's specific. goto is the
language construct which causes an
unconditional branch. Alternatives
depend on using structures
supporting conditional branches,
with a degenerate always-true
condition.
The label documents the intent
without extra comments.
The reader doesn't have to scan the
intervening code for early breaks
(although it's still possible for an
unprincipled hacker to simulate
continue with an early goto).
Rules:
Pretend that the gotophobes didn't
win. It's understood that the above
can't be used in real code because
it goes against established idiom.
Assume that we have all heard of
'Goto considered harmful' and know
that goto can be used to write
spaghetti code.
If you disagree with an example,
criticize it on technical merit
alone ('Because people don't like
goto' is not a technical reason).
Let's see if we can talk about this like grown ups.
Edit
This question seems finished now. It generated some high quality answers. Thanks to everyone,
especially those who took my little loop example seriously. Most skeptics were concerned
by the lack of block scope. As #quinmars pointed out in a comment, you can always put braces around the
loop body. I note in passing that for(;;) and while(true) don't give you the braces
for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more
of your brain power on this trifle - I can live with the harmless and idiomatic for(;;) and while(true) (just as well if I want to keep my job).
Considering the other responses, I see that many people view goto as something you always
have to rewrite in another way. Of course you can avoid a goto by introducing a loop,
an extra flag, a stack of nested ifs, or whatever, but why not consider whether goto is
perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that
even adding a flag is too high a price to pay. I like my variables to represent things in
the problem or solution domains. 'Solely to avoid a goto' doesn't cut it.
I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a goto of all the posted answers, certainly
if you measure it by the contortions a hater has to go through to avoid it.
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
/* everything has succeeded */
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
The classic need for GOTO in C is as follows
for ...
for ...
if(breakout_condition)
goto final;
final:
There is no straightforward way to break out of nested loops without a goto.
Here's my non-silly example, (from Stevens APITUE) for Unix system calls which may be interrupted by a signal.
restart:
if (system_call() == -1) {
if (errno == EINTR) goto restart;
// handle real errors
}
The alternative is a degenerate loop. This version reads like English "if the system call was interrupted by a signal, restart it".
If Duff's device doesn't need a goto, then neither should you! ;)
void dsend(int count) {
int n;
if (!count) return;
n = (count + 7) / 8;
switch (count % 8) {
case 0: do { puts("case 0");
case 7: puts("case 7");
case 6: puts("case 6");
case 5: puts("case 5");
case 4: puts("case 4");
case 3: puts("case 3");
case 2: puts("case 2");
case 1: puts("case 1");
} while (--n > 0);
}
}
code above from Wikipedia entry.
Knuth has written a paper "Structured programming with GOTO statements", you can get it e.g. from here. You'll find many examples there.
Very common.
do_stuff(thingy) {
lock(thingy);
foo;
if (foo failed) {
status = -EFOO;
goto OUT;
}
bar;
if (bar failed) {
status = -EBAR;
goto OUT;
}
do_stuff_to(thingy);
OUT:
unlock(thingy);
return status;
}
The only case I ever use goto is for jumping forwards, usually out of blocks, and never into blocks. This avoids abuse of do{}while(0) and other constructs which increase nesting, while still maintaining readable, structured code.
I have nothing against gotos in general, but I can think of several reasons why you wouldn't want to use them for a loop like you mentioned:
It does not limit scope hence any temp variables you use inside won't be freed until later.
It does not limit scope hence it could lead to bugs.
It does not limit scope hence you cannot re-use the same variable names later in future code in the same scope.
It does not limit scope hence you have the chance of skipping over a variable declaration.
People are not accustomed to it and it will make your code harder to read.
Nested loops of this type can lead to spaghetti code, normals loops will not lead to spaghetti code.
One good place to use a goto is in a procedure that can abort at several points, each of which requires various levels of cleanup. Gotophobes can always replace the gotos with structured code and a series of tests, but I think this is more straightforward because it eliminates excessive indentation:
if (!openDataFile())
goto quit;
if (!getDataFromFile())
goto closeFileAndQuit;
if (!allocateSomeResources)
goto freeResourcesAndQuit;
// Do more work here....
freeResourcesAndQuit:
// free resources
closeFileAndQuit:
// close file
quit:
// quit!
#fizzer.myopenid.com: your posted code snippet is equivalent to the following:
while (system_call() == -1)
{
if (errno != EINTR)
{
// handle real errors
break;
}
}
I definitely prefer this form.
Even though I've grown to hate this pattern over time, it's in-grained into COM programming.
#define IfFailGo(x) {hr = (x); if (FAILED(hr)) goto Error}
...
HRESULT SomeMethod(IFoo* pFoo) {
HRESULT hr = S_OK;
IfFailGo( pFoo->PerformAction() );
IfFailGo( pFoo->SomeOtherAction() );
Error:
return hr;
}
Here is an example of a good goto:
// No Code
I've seen goto used correctly but the situations are normaly ugly. It is only when the use of goto itself is so much less worse than the original.
#Johnathon Holland the poblem is you're version is less clear. people seem to be scared of local variables:
void foo()
{
bool doAsuccess = doA();
bool doBsuccess = doAsuccess && doB();
bool doCsuccess = doBsuccess && doC();
if (!doCsuccess)
{
if (doBsuccess)
undoB();
if (doAsuccess)
undoA();
}
}
And I prefer loops like this but some people prefer while(true).
for (;;)
{
//code goes here
}
My gripe about this is that you lose block scoping; any local variables declared between the gotos remains in force if the loop is ever broken out of. (Maybe you're assuming the loop runs forever; I don't think that's what the original question writer was asking, though.)
The problem of scoping is more of an issue with C++, as some objects may be depending on their dtor being called at appropriate times.
For me, the best reason to use goto is during a multi-step initialization process where the it's vital that all inits are backed out of if one fails, a la:
if(!foo_init())
goto bye;
if(!bar_init())
goto foo_bye;
if(!xyzzy_init())
goto bar_bye;
return TRUE;
bar_bye:
bar_terminate();
foo_bye:
foo_terminate();
bye:
return FALSE;
I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.
#include <stdio.h>
#include <string.h>
int main()
{
char name[64];
char url[80]; /*The final url name with http://www..com*/
char *pName;
int x;
pName = name;
INPUT:
printf("\nWrite the name of a web page (Without www, http, .com) ");
gets(name);
for(x=0;x<=(strlen(name));x++)
if(*(pName+0) == '\0' || *(pName+x) == ' ')
{
printf("Name blank or with spaces!");
getch();
system("cls");
goto INPUT;
}
strcpy(url,"http://www.");
strcat(url,name);
strcat(url,".com");
printf("%s",url);
return(0);
}
#Greg:
Why not do your example like this:
void foo()
{
if (doA())
{
if (doB())
{
if (!doC())
{
UndoA();
UndoB();
}
}
else
{
UndoA();
}
}
return;
}