Weirdest C++ stack empty() fault - c++

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
}

Related

Can you return to main instead of returning 0

I am relearning C++. I was quite a noob before but I am going over the basics again and hopefully going further. My main question is, at the end of the main loop, is there a way to call the function again instead of ending the programme by returning 0. So something along the line of:
........
return main;
}
The standard C++ says...
5.2.2.9 Recursive calls are permitted, except to the function named main
"The Standard" at https://isocpp.org/std/the-standard
You could certainly do something like this:
int main()
{
while(1==1) /* (1==1) is always true. */
{
/* Do the hokey pokey, turn yourself around, and do whatever else you feel like doing. */
}
/* The program will never reach this point unless you explicitly break out of the loop. */
return 0;
}
This will result in a program that just repeats over and over again until you kill it. This is, of course, bad style, but it will work if you just need to get something up and running quickly.
As Trevor Hickey mentions, you could call break from within the loop and break out.

While loop within a while loop, how to both conditions work?

I am writing a program that involves reading numerous bits of data from files, and I have ran into a bit of a dilemma (being a relatively inexperienced programmer). If a while loop is contained within another while loop, which conditions need to be fulfilled in order to leave the loop?
My specific situation is shown below, (emptyLineFound is a Boolean set to be true when empty line has been found)
while(!file.eof()) {
....
while(!emptyLineFound) {
....
}
}
Which condition takes priority? Must they both be satisfied to leave that section of code? e.g if it is at the end of the file and an empty line can not be found as there is no line, will it mess up?
Both sections do not have to be satisfied for the nested while to exit.
while(!file.eof()) {
Will continue to run while the file is not at the end of the stream.
while(!emptyLineFound) { .... }
Will continue to run while an empty line is not found.
Once an empty line is found, you will drop out of the nested loop and the parent loop will continue until the condition is satisfied (EOF is reached).
While(ExitCondition)
{
// you are at this point if ExitCondition fails .
while(another-ExitCondition)
{
// you are at this point if another-ExitCondition fails
}
// you will come at this point once another-ExitCondition becomes true
}
// you will be at this point once ExitCondition becomes true .
In your question, the inner loop will end when emptyLineFound is true. The outer loop will continue until file.eof() is true. Presumably something in the inner loop sets emptyLineFound to false before the next loop.
Note that the conditions are tested as the code gets there, so, in theory you could have something like this:
while(!file.eof())
{
while(!emptyLineFound)
{
... do some reading ...
if (file.eof())
{
... reset file so we can do more reading ...
}
}
}
and the loop would continue forever, except if file.eof() is true from the very beginning of the loop.
By the way, in general, using !file.eof() as a loop control is a pretty poor idea. It is much better to use the read operation itself, e.g. while (file >> var) ... - since while (!file.eof()) tends to lead to an extra iteration, because file.eof() isn't true until you have read PAST the end.
Each time the outer loop is repeated, the inner loops are reentered and start new.
Perhaps the code becomes clear if expressed differently:
void f()
{
// ...
while (!file.eof()) {
// ...
}
}
int main()
{
// ...
while (!emptyLineFound) {
f();
}
}
This is semantically the same as your program; it has the same overall logic.
From here, you can clearly see that a call to f() will not terminate until f.eof() is true, and that main will repeatedly call f() (and thus perform the "inner" loop) until emptyLineFound is true.

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.

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

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?

Extra brace brackets in C++ code

Sometimes you run into code that has extra brace brackets, that have nothing to do with scope, only are for readability and avoiding mistakes.
For example:
GetMutexLock( handle ) ;
{
// brace brackets "scope" the lock,
// must close block / remember
// to release the handle.
// similar to C#'s lock construct
}
ReleaseMutexLock( handle ) ;
Other places I have seen it are:
glBegin( GL_TRIANGLES ) ;
{
glVertex3d( .. ) ;
glVertex3d( .. ) ;
glVertex3d( .. ) ;
} // must remember to glEnd!
glEnd() ;
This introduces a compiler error if the mutex isn't freed (assuming you remember both the } and the Release() call).
Is this a bad practice? Why?
If it isn't one, could it change how the code is compiled or make it slower?
The braces themselves are fine, all they do is limit scope and you won't slow anything down. It can be seen as cleaner. (Always prefer clean code over fast code, if it's cleaner, don't worry about the speed until you profile.)
But with respect to resources it's bad practice because you've put yourself in a position to leak a resource. If anything in the block throws or returns, bang you're dead.
Use Scope-bound Resource Management (SBRM, also known as RAII), which limits a resource to a scope, by using the destructor:
class mutex_lock
{
public:
mutex_lock(HANDLE pHandle) :
mHandle(pHandle)
{
//acquire resource
GetMutexLock(mHandle);
}
~mutex_lock()
{
// release resource, bound to scope
ReleaseMutexLock(mHandle);
}
private:
// resource
HANDLE mHandle;
// noncopyable
mutex_lock(const mutex_lock&);
mutex_lock& operator=(const mutex_lock&);
};
So you get:
{
mutex_lock m(handle);
// brace brackets "scope" the lock,
// AUTOMATICALLY
}
Do this will all resources, it's cleaner and safer. If you are in a position to say "I need to release this resource", you've done it wrong; they should be handled automatically.
Braces affect variable scope. As far as I know that is all they do.
Yes, this can affect how the program is compiled. Destructors will be called at the end of the block instead of waiting until the end of the function.
Often this is what you want to do. For example, your GetMutexLock and ReleaseMutexLock would be much better C++ code written like this:
struct MutexLocker {
Handle handle;
MutexLocker(handle) : handle(handle) { GetMutexLock(handle); }
~MutexLocker() { ReleaseMutexLock(handle); }
};
...
{
MutexLocker lock(handle);
// brace brackets "scope" the lock,
// must close block / remember
// to release the handle.
// similar to C#'s lock construct
}
Using this more C++ style, the lock is released automatically at the end of the block. It will be released in all circumstances, including exceptions, with the exceptions of setjmp/longjmp or a program crash or abort.
It's not bad practice. It does not make anything slower; it's just a way of structuring the code.
Getting the compiler to do error-checking & enforcing for you is always a good thing!
The specific placement of { ... } in your original example serves purely as formatting sugar by making it more obvious where a group of logically related statements begins and where it ends. As shown in your examples, it has not effect on the compiled code.
I don't know what you mean by "this introduces a compiler error if the mutex isn't freed". That's simply not true. Such use of { ... } cannot and will not introduce any compiler errors.
Whether it is a good practice is a matter of personal preference. It looks OK. Alternatively, you can use comments and/or indentation to indicate logical grouping of statements in the code, without any extra { ... }.
There are various scoping-based techniques out there, some of which have been illustrated by the other answers here, but what you have in your OP doesn't even remotely look anything like that. Once again, what you have in your OP (as shown) is purely a source formatting habit with superfluous { ... } that have no effect on the generated code.
It will make no difference to the compiled code, apart from calling any destructors at the end of that block rather than the end of the surrounding block, unless the compiler is completely insane.
Personally, I would call it bad practice; the way to avoid the kind of mistakes you might make here is to use scoped resource management (sometimes called RAII), not to use error-prone typographical reminders. I would write the code as something like
{
mutex::scoped_lock lock(mutex);
// brace brackets *really* scope the lock
} // scoped_lock destructor releases the lock
{
gl_group gl(GL_TRIANGLES); // calls glBegin()
gl.Vertex3d( .. );
gl.Vertex3d( .. );
gl.Vertex3d( .. );
} // gl_group destructor calls glEnd()
If you're putting code into braces, you should probably break it out into its own method. If it's a single discrete unit, why not label it and break it out functionally? That will make it explicit what the block does, and people who later read the code won't have to figure out.
Anything that improves readablity IMHO is good practice. If adding braces help with the readability, then go for it!
Adding additional braces will not change how the code is compiled. It won't make the running of the program any slower.
This is much more useful (IMHO) in C++ with object destructors; your examples are in C.
Imagine if you made a MutexLock class:
class MutexLock {
private:
HANDLE handle;
public:
MutexLock() : handle(0) {
GetMutexLock(handle);
}
~MutexLock() {
ReleaseMutexLock(handle);
}
}
Then you could scope that lock to just the code that needed it by providing an new scope with the braces:
{
MutexLock mtx; // Allocated on the stack in this new scope
// Use shared resource
}
// When this scope exits the destructor on mtx is called and the stack is popped