Can someone please check my timer program in C++ - c++

I want to write a program that checks if the changes in the values of X,Y and Z don't exceed a difference of 10 within 5 seconds, the initialValues() function should be called.
I have written the following program but it crashes while running and the program doesn't work. Then I have to force close the program.
below is the main part of my program for timer. My program doesn't crash when I remove this specific part.
How do I fix this?
while(X<=X+10 || X>=X-10 && Y<=Y+10 || Y>=Y-10 && Z<=Z+10 || Z>=Z-10)
{
clock_t t;
t = clock();
t = clock()-t;
float timer = t/CLOCKS_PER_SEC;
if(timer==5)
{
initialValues(X,Y,Z);
cout<<"X = "<<initialX<<" Y = "<<initialY<<" Z = "<<initialZ<<endl;
}
}

You don't say what the function initialValues does, so we cannot know whether something dodgy is done there.
However, it seems likely that you have an infinite loop. Check the conditions in the while loop, and insert brackets to separate conditions that should be evaluated together, such as, for exmaple:
while( ( X<=X+10 || X>=X-10 ) && ( Y<=Y+10 || Y>=Y-10 ) && ( Z<=Z+10 || Z>=Z-10) )
Note the extra brackets.
In particular, you should check whether the conditions that you have specified are always true, as suggested by another user. It seems to me that X<=X+10 always, and the same applies to the rest of conditions.

Related

Is it good practice if container's size is validated and accessing an element under same conditional statement?

Which one of the following code is more preferable between two of them and why?
1.
std::stack<int>stk;
//Do something
if( stk.empty() == true || stk.top() < 10 )
{
//Do something.
}
or
2
std::stack<int>stk;
//Do something
if( stk.empty() == true )
{
//Do something.
}
else if( stk.top() < 10 )
{
//Do something.
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first). So, expression stk.empty() || stk.top() < 10 is safe and good practice, stk.top() is only called if stk.empty() evaluates to false. In other words, the operators were designed to enable such usage.
It entirely depends on the use case. In the first code, you have an OR condition for empty stack and checking the value of element if an element exist. So, it's clear and you can proceed with the code.
In the 2nd code, you want to execute something different for both the conditions. Hence you have put the conditions in a if else loop.
Good practise comes into sense when you don't want your code to break or pass corner test cases.You might not wan't something in your code when the stack is empty.
std::stack<int>stk;
if(stk.top() < 10 )
{
//Do something.
}
else if(stk.empty() == true)
{
//Do something
}
This will generate run time error since the stack is empty but you are accessing top element before checking the stack empty condition.
Snap of the error
I hope the answer makes it clear.

How to infinite loop or loop up to a limit without an if-else

I'm wondering if there's a way to write a function that takes one input, a max count for the number of times to loop, that will do an infinite loop if the number is negative, without using an if-else
i.e.
void func(int nAttempts) // if nAttempts <= 0, do an infinite loop
{
if ( nAttempts <= 0 )
{ // do an infinite loop
}
else
{ // do a loop up to nAttemtps
}
}
I'd like to know if there's a way to do that without an if-else
while ((nAttempts < 0) || (nAttempts-- > 0)) {...}
but... why? This makes your code less readable, where an if/else makes it pretty clear what your intentions are.
I take it this is some sort of a trick question? Here's my take:
void f(int n)
{
n < 0 ? []{ while(true); }() : [&]{ while(n--); }() ;
}
The loop itself has a conditional inside of it, it is not an explicit if, but it is a branch. The actual evaluation of that expression is turing complete as well due to lazy evaluation. As a result, this question is kind of nonsensical since even without an if statement, there is still a conditional statement taking place. However, the answer to your question is the following:
void optionalInfiniteLoop(int nAttempts){
while(nAttempts < 0 || nAttempts-- != 0){
...
}
}
Looking at this and understanding lazy evaluation, nAttempts < 0 is evaluated first. If it is true, the || does not need to run, and so it will never wrap the int around by subtracting too far. If it is false, then the second part of the while loop evaluates until nAttempts becomes 0. I don't think you'd save anything by doing this, and indeed, you may be forcing the computer to do slightly more work every iteration by checking nAttempts < 0 instead of just doing that once.
The performance is almost definitely not going to be measurable in the context of an application, and I think the above looks cleaner, but it's really more of a stylistic approach than a technical one.
void func( int nAttempts )
{
while (nAttempts)
{
// do stuff
--nAttempts;
}
}
Basically at the end of every iteration, you subtract one 'try'. When it hits 0 you stop. If it was already negative to begin with, it will become increasingly negative (though I suppose eventually it would overflow).

Iterator inside of loop will not increment

I'm attempting to compare two string arrays. Whenever I get to the while loop inside of the if statement, I get stuck in an infinite loop because even though I have an iterator inside of the loop, it doesn't increment. I have the cout<< finder; in the loop just to see what finder is at, and it never increments above zero. If anyone could help I'd really appreciate it.
if (memory[p] == "J")
{
if (is_number(memory[p+1]))
{
worker = atoi(memory[p+1].c_str());
p = worker;
continue;
}
else
{
int finder = 0;
while (memory[p+1] != Symtablelab[finder])
{
cout << finder;
finder = finder + 1;
}
if (memory[p+1] == Symtablelab[finder])
{
int k = Symtablepos[finder];
worker = atoi(memory[k].c_str());
p = worker;
continue;
}
}
}
You said finder never increments above zero. Does it print finder = 0 at all? If it does, it means
memory[p+1] = Symtablelab[1]
just after 1st iteration, so the while loop gets terminated and finder sticks at 1.
EDIT
If you say, it prints finder = 0 continuously inside the while statement, then probably you have if (memory[p] == "J") inside an outer for or while (looping) statement.
If it is continuously printing finder and it is 0, then I must ask if this whole code snippet you posted is enclosed in a while statement that you did not post. It makes absolutely no sense that the while loop included in the statement you posted would not be incrementing finder if it is the loop that gets stuck in an infinite loop.
Or the other possibility is that Symtablelab has overriden the '[' ']' operators. If neither of these things are true, that something incredibly wonky is going on.

Stuck in Infinite Recursion

I have this function to solve a maze in C++, but when I run the program I get a Bad Access Error in the recursion. I think in may be an infinite loop. I have no idea where and what is going wrong.
bool Solve_Maze(int coorx,int coory) {
if((Map[coorx][coory]==Start)||(Map[coorx][coory]==path)) {
Map[coorx][coory]=wall;
Solve_Maze(coorx+1,coory);
Solve_Maze(coorx-1,coory);
Solve_Maze(coorx,coory+1);
Solve_Maze(coorx,coory-1);
}else if(Map[coorx][coory]==End) {
cout<<"You Solved the Maze!"<<endl;
delete Map;
return(true);
}
}
1) You are not returning any value in if statement
2) Map[coorx][coory] always assigned to wall in all function call..Does wall refers to a global state?
I changed the function to return void since the value wasn't properly being returned up the stack. In this case you will just use the global found variable to check if the end was found. (this will require you to set 'found = false' every time before you run the function).
bool found = false;
You also want to do some input validation
if( coorx > maxX || coorx < 0 || coory > maxY || coory < 0) return;
You will need to replace maxX and maxY with 1 more than your maximum values for coorx and coory. That will ensure you don't get a bad access error.
bool found = false; // this will be global scope or pass it by reference
Solve_Maze(x,y);
// if(found) - found will be true if you found the end
void Solve_Maze(int coorx,int coory) {
if( coorx > maxX || coorx < 0 || coory > maxY || coory < 0) return;
else if(((Map[coorx][coory]==Start)||(Map[coorx][coory]==path))) {
Map[coorx][coory]=wall;
Solve_Maze(coorx+1,coory);
Solve_Maze(coorx-1,coory);
Solve_Maze(coorx,coory+1);
Solve_Maze(coorx,coory-1);
}else if(Map[coorx][coory]==End) {
cout<<"You Solved the Maze!"<<endl;
delete Map;
found = true;
}
}
Run it in a debugger (gdb or dbx). Compile with the -g flag so your program can be debugged. If you don't know how to use a debugger, google "dbx cheatsheet." You can isolate where it's stuck in the loop (if your guess is right) and step your way through. The total time it will take you to become proficient enough in a debugger to do this is, and to actually do it, is less than the amount of time you have spent thinking about it already.
No sarcasm is intended - people really do often overestimate the work in learning a debugger, so I want to really assert the point that it's worth it even for a simple problem, and tremendously pays off for big problems.

Strange program and debugger if statement behavior

This is a sanity check because I've lost mine.
I have a method IsCaptured() which compares an enum state member to a given value and returns a bool. I use this in conjunction with a mouse threshold check to determine if a drag begin message should be sent and a drag operation begun. The problem is this is being triggered on mouse move when it shouldn't be. I've added trace messages as follows:
TRACE(L"%s\n", (IsCaptured()) ? L"true" : L"false");
CPoint delta = pt - m_trackMouse;
static CPoint thresh(GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG));
if (IsCaptured() &&
abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
{
TRACE(L"%s\n", (IsCaptured()) ? L"true" : L"false");
// Send message to enter drag mode
bool bDrag = ::SendMessage(m_trackWnd, WM_DD_BEGIN, ::GetDlgCtrlID(m_trackWnd), (LPARAM)(void*)&m_info) != 0;
// ...
}
Now the strange part, the output:
false
false
The method is implemented like so and m_dragState is set to NONE until there is a button down intercepted:
enum { NONE, CAPTURED, DRAGGING };
bool IsCaptured() const { return m_dragState == CAPTURED; }
I've tried rebuilding the entire solution to no avail. I'm running VS2010 Debug 64-bit and the program is a single threaded MFC app. What the $##! is going on here?
There's nothing strange in your output. && has higher precedence than ||, which is why your
if (IsCaptured() &&
abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
is interpreted as
if ((IsCaptured() && abs(delta.x) >= thresh.x) ||
abs(delta.y) >= thresh.y)
I.e. if the abs(delta.y) >= thresh.y condition is met, then the result of the entire if condition does not depend on your IsCaptured() at all.
The compiler does not care that you "expressed" your intent in line breaks. Operator precedence matters. Line breaks don't.
What you apparently were intending to do was
if (IsCaptured() &&
(abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y))
Note the placement of extra braces around the operands of || subexpression.
Think of this as:
(IsCaptured() && abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
this:
(false && true) || true
Your IsCaptured() doesn't have to be true to progress, so it can quite possibly be false in both printouts.
You should probably make sure first that the two false's do not refer both to the first trace line.
If the second trace line is actually printing false here, you probably have a classic race condition on your hands and need to protect against it.