Both if and else part are executing [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
/*Q_INVOKABLE*/ void LinkDestUI::selectDeselectSingleDestination(int iXmlId)
{
for(const auto &subNode : m_nodeColl)
{
if(bMultipleSelect())
{
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"1 ";
subNode->setbSelected(!subNode->bSelected());
}
}
else
{
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"2 ";
subNode->setbSelected(!subNode->bSelected());
}
else
{
LOG(Severity_Error)<<"3 ";
subNode->setbSelected(false);
}
}
}
}
When i execute my code then compiler goes to else part and exceute both if and else statement inside the else part. why?

That seems ... (temporarily increasing my tactfulness attribute so as to avoid offending) ... rather unlikely :-)
It's probably because the code is being entered more than once and you're just assuming it's executing both parts because of the output.
My advice would be to change the code in the outer else to be:
LOG(Severity_Error)<<"Starting inner if ";
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"2 ";
subNode->setbSelected(!subNode->bSelected());
}
else
{
LOG(Severity_Error)<<"3 ";
subNode->setbSelected(false);
}
LOG(Severity_Error)<<"Ending inner if ";
You should not see both blocks executing without an intervening end/start message set.

Related

Parenthesis Checker gfgs [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The following code is giving segmentation fault can anyone tell why. this is a geeks for geeks practice problem (Parenthesis Checker) .
Q- Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{()()}” and 'false' for exp = “[(])”.
bool check(string s)
{
stack<char> save;
int x = s.size();
for(int i=0;i<x;i++)
{
if(s[i]=='{' || s[i]=='['|| s[i]=='(')
{
save.push(s[i]);
}
else if(s[i]=='}'){
if(save.top()=='{')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==']')
{
if(save.top()=='[')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==')')
{
if(save.top()=='(')
{
save.pop();
}
else{
return false;
}
}
}
if(!save.empty())
{
return false;
}
else{
return true;
}
}
You have a chance to seg-fault when the stack is empty and the next character in the string is a closing paren.
E.g. if the input string is ")" or "())" your program will not behave as intended.
You will need to change the if statements from
if (save.top() == '('){...} to if (!save.empty() && save.top() == '('){...}
And similarly for every other case where you check save.top (The preceeding code does not guarantee that the stack is not empty at that given point).
Note: You would also need to do this for each occurrence of pop as well, but the guards before top() will guarantee that the stack is not empty when you then pop.

while exercise with return in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I've just started coding in c++ and now I have an exercise that I can't do because the code seems to not work.
I've to find the max and the min with a sequence of n numbers (in this case i already know that they are 4). I've to use while.
I've just started so I don't know how return properly works...
there aren't syntactical errors but when I run it ask me the number but then it says that the algorithm ends with 0 value.
Here's the code, if you can help me thank you!
#include <iostream>
using namespace std;
main ()
{ float mag,min,i,a;
mag=0;
min=0;
i=0;
while (1)
{
if (i<5)
{ cout<<"insert a number"<<endl;
cin>>a;
if (i = 0)
{ mag=a;
min=a;
}
else
{ if (a<min)
{ min=a;
}
else
{ if (a>mag)
{ mag=a;
}
}
}
i=i+1;
}
else
{ cout<<"maggiore= "<<mag<<endl<<"min= "<<min<<endl;
}
return 0;
}
system ("pause");
}
I see at minimum one problem:
if (i = 0)
This is assignment of i to 0 and compare the result of assignment, which is always false if you assign a 0.
I believe you want only compare and not assign, so you have to use:
if ( i == 0 )
The next problem is
return 0;
This will always end the current function, if the function is main(), it will terminate your program. In your case, you can simply remove the return statement, as in main it will return 0 by default if the function ends.
But if you use
while (1)
without any return, your program runs endless. I don't know what is the expected behavior.
Rest looks fine.
Hint: Your indentation is a bit special. :-)
1st it should be i==0 not i=0 in the if
2nd you should place that return 0 after that cout maggiore or it will close after the first loop
3rd you don't need that system pause there. It does literally nothing. You should either remove it or place it exactly before the return.

What is the difference between the two codes in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I was trying the problem Hash Tables: Ice Cream Parlor on Hackerrank. It is a simple question, but here is the bizzare situation i got to. How does the change of data structure matter?
Case 1:
void whatFlavors(vector<int> cost, int money) {
int ans1,ans2;
vector<int> arr(100,0); //notice this
for(int i=0;i<cost.size();i++){
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
if(ans1>ans2){
cout<<ans2<<" "<<ans1<<endl;
}else{
cout<<ans2<<" "<<ans1<<endl;
}
break;
}
else{
arr[cost[i]]=i+1;
}
}
}
And output is:
Case 2:
code:
void whatFlavors(vector<int> cost, int money) {
int arr[100]={0}; //notice this
int ans1,ans2;
for(int i=0;i<cost.size();i++){
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
if(ans1>ans2){
cout<<ans2<<" "<<ans1<<endl;
}else{
cout<<ans2<<" "<<ans1<<endl;
}
break;
}
else{
arr[cost[i]]=i+1;
}
}
}
output:
Let's just notice this part of your code:
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
This means that your expect money-cost[i] to be negative for some values of i. So you end up reading locations that are outside your array (vector or array) which will lead to undefined behavior in both cases.

C++ Queue error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my Queue declaration here
// TODO: Declare a queue here - e.g. as a global variable
queue<string>myQueue;
This here is where I think my problem is. Whenever I run the program, I get an error stating "deque iterator not dereferencable."
string receiveMessage()
{
string messageValue = noMessage; // Don't change this value unless there is a message - default is improtant
messageQueueMutex.lock();
try
{
// TODO: Set hasMessages to true if your queue is not empty, otherwise set it to false:
if(!myQueue.empty())
{
bool hasMessages = true;
}
else
{
bool hasMessages = false;
}
// TODO: Remove the first message from your queue and place it in messageValue:
messageValue = myQueue.front();
myQueue.pop();
}
catch (...)
{
cout << "Exception occurred - check your code!" << endl;
}
messageQueueMutex.unlock();
return messageValue;
}
You don't need to use unlock() here, std::mutex will automatically unlock when it goes out of scope. Also, hasMessages will not be accessible after the if-else statement b/c it is declared inside the scopes of the if-else statement. So, you need to do:
bool hasMessages;
if(!myQueue.empty())
{
hasMessages = true;
}
else
{
hasMessages = false;
}
If the queue is empty, this code will still attempt to remove the first element from the queue. If you don't believe me, just ask your rubber duck.
This is, of course, undefined behavior.

continue statement inside for loop and if condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have following code snippet and the output i am getting is 4. Please explain me if it takes i=2 or 0. I am confused. And How output was 4?
int main() {
int i=2;
for(i=0;i<2;i++) {
i=i%3;
if(i==2) {
i++;
continue; }
else
++i;
}
printf("%d",i);
}
The loop starts with i = 0. Both the if and the else to exactly the same thing. Increment i and continue.
If you use a bit of logic, the whole block can be reduced to i++ (i = i % 3 has no effect since i < 2).
It's not possible to get 4 with the code you posted.
The output cannot be 4 for the program you posted, because by the time the loop breaks, the value of i would be 2, not 4 and the loop will run exactly once.
Also, your code never enters the if block, because the condition is i==2 which can never be true inside the for loop, as by that time the loop would be exited.
So your code is equivalent to this:
int main() {
int i=2;
for(i=0;i<2;i++) {
i++;
}
printf("%d",i);
}