Simple if statement not evaluating to true when it should - c++

if ((!m_pMediaPage->PageLayer() || !m_pMediaPage->LoadState()) &&
!m_pMediaPage->m_bRequestList)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
GetListInfo() does not get executed when all values are 0.
PageLayer() and LoadState() return ints and m_bRequestList is an int.
Basically rewritten as this:
if ((!0 || !0) && !0) -or- if ((1 || 1) && 1)
I can only assume that the values being evaluated by the if statement aren't really as seen by the debugger.
I am using visual studio 2005 and put breakpoints on line 1 & 4 to examine the values and see if it executes into the if statement. I am not sure how else to debug this.
Like I said, each of the 3 values are 0 as viewed by the debugger when at breakpoint 1.
Functions in .h:
int PageLayer() {return m_iCurrentLayer;} - protected
BOOL LoadState() {return m_bLoadDone;} - protected
BOOL:
typedef int BOOL;

This conditional statement looks as if it would be executed if all values return from the different functions return zero. If the body of the function isn't executed, I would debug the problem as follows:
Log the values of all functions prior to the if-statement:
std::cout << "page-layer=" << !m_pMediaPage->PageLayer() << ' '
<< "load-state=" << !m_pMediaPage->LoadState() << ' '
<< "request-list=" << !m_pMediaPage->m_bRequestList << '\n';
Yes, the debugger should show these values as well but I have great faith in the values being printed to be the values actually evaluated.
If that doesn't give the necessary insight into what goes wrong, I would start breaking down the condition into separate parts and verify success at each level, e.g.:
if (!m_pMediaPage->PageLAyer()) {
std::cout << "page-layer is not set\n";\
}
if (!m_pMediaPAge->LoadState()) {
std::cout << "load-state is not set\n";
...
If this still doesn't give any insight, I'd start suspecting that the functions return funny values and I would verify that the different results are funny values and I would start looking at the output after preprocesing using the -E option.

You tagged the question as VS2005; do you have all relevant service packs installed to ensure you aren't running into some long-fixed compiler issue?
Secondly, the functions you've listed appear to be very simple setters (you might want to make them const, although that is unrelated to your problem).
You're stepping thru with the debugger, it might therefore be valuable to check your assertion that they are all zero:
bool plCond = (m_pMediaPage->PageLayer());
bool lsCond = (m_pMediaPage->LoadState());
bool rlCond = (m_pMediaPage->m_bRequestList);
bool getListInfoCond = ((!cond1 || !cond2) && !cond3);
if (getListInfoCond)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
If this fixes the problem, you either have a heisenbug or a stack/memory stomp.
If this doesn't fix the problem, it may home in on the cause.
If this DOES fix the problem, you may want to consult the assembly for the code and see if you have somehow tripped a compiler bug.

Related

Is there a compiler difference between an if-check and inline conditional?

I've recently begun using flags to handle an input loop's validity condition so it can be checked elsewhere inside the loop rather than having to redo the same check multiple times. However, I'm unsure how best to assign the flag. Is there a generally standard practice regarding this, or just personal style? What, differences are there in the compiled code, if any?
For example, instead of the following code:
bool isValidSize;
do {
std::cout << "Enter the font size (8-12): ";
std::cin >> fontSize;
if (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE) {
isValidSize = true;
} else {
isValidSize = false;
std::cout << "Invalid size. ";
}
} while (!isValidSize);
the if-statement can be changed to make it more clear what isValidSize is set to at a glance:
isValidSize = (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE);
if (!isValidSize) {
std::cout << "Invalid size. ";
}
Would this be compiled as an extra if-check? Is there any portability benefit to having the assignment separate from anything else? From just looking at the code, it seems the benefit of the first way is possibly only one branch but an additional assignment per rep and also has an else?
There are no differences: proof.
Tested on GCC 6.3 with optimisations (-O3).
Go for what you think is the more readable one.

Returning void from method to prevent execution

I am attempting to exit a method which returns void after checking a condition (I realize this would be easier if I threw an exception, but I'm trying to avoid that for this project). I have the code below, which should return out of the if statement, if I am interpreting it correctly, but the entire method is still executing. Is there a problem in the code somewhere (I can post more if needed), or is there a better way to write this without exception handling?
void Rational::divide(Rational b) {
if (b.numerator == 0) {
cout << "Cannot divide by zero." << endl;
return;
} else if (b.numerator != 0) {
numerator = numerator * b.denominator;
denominator = denominator * b.numerator;
reduce();
}
}
EDIT: I've updated the code to reflect some suggestions; just to clarify, the if statement itself is executing correctly (if b is zero, I get the error message) - once the error message is printed, the remainder of the method continues to run.
EDIT 2: Updated with else if revision.
And that is what you are doing. You probably want to do something like this in your ifstatement: if((double)b.denominator == 0.f).
You should also be careful when comparing with floats or double due to the way they are represented in memory. It will almost never be exactly zero, so you should compare with an epsilon.

Unable to reduce the code (combine cout with exit)

I'm allowed to insert only 10 lines (strict) of codes into my program. I have optimized to program to a concise one. I have posted the code below.
if (std::find(outvar.begin(), outvar.end(), line[x].tokens[0]) == outvar.end() || (std::find(inputs.begin(), inputs.end(), line[x].tokens[4]) == inputs.end())
{
cerr << "Undefined variable " << endl;
exit(1);
}
if (opr[x].type == "MUL" && opr[x1].asap_value == my_cycle + 1)
{
opr[x1].asap_value = my_cycle + 2;
update_slack();
update_matrix(opr[x1].opid, 0);
}
if (latency < (opr[p2].asap_value + opr[p2].latency_op - 1) || opr[p2].asap_value == 0)
{
cerr << "Latency value is too less for this circuit \n"; return -1;
}
This alone takes 10 lines and I have 2 more compulsory lines of codes that has to be added. I'n unable to further reduce it. Basically I'm looking to combine the err(cout) statement along with the exit (return) statement into a single statement.
Any help will be greatly appreciated.
Thank you
You could make this all into one line using commas:
opr[x1].asap_value = my_cycle + 2, update_slack(), update_matrix(opr[x1].opid, 0);
Not sure if this is considered cheating. You haven't specified what the rules are exactly.
You need to understand that there is no obvious relationship between the number of statements and the code efficiency. That is because, for example the statement cout<<x; is not a single instructions for your processor. There can be hundreds or even thousands of instructions that the processor must execute in order to achieve the goal of that statement. Also, there are some statements, like a = b + c; that are translated into 2-3 instructions.
So, by reducing the number of statements, you don't optimize the code. There are other ways of optimization, like using a more efficient algorithm.

sense of if - how is it possible that works

I'm watching Mojam (live games programming, on HumbleBundle) and I saw this piece of code there
(here is screenshot of code)
I'm wondering how come the condition expression in last if statement (which is !wasmoving && ismoving) ever evaluates to true (it does, programmer compiled it and animation was running).
I've tried this in my compiler
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
bool ismoving=5>0;
bool wasmoving=ismoving;
cout << "ismoving"<< ismoving << " oraz wasmoving " << wasmoving << endl;
if (!wasmoving && ismoving) cout << "1st = true 2nd = true" << endl;
system("PAUSE");
return 0;
}
and of course if the last if takes false path, nothing happens.
Could anyone explain how it's posssible that code from screenshot worked?
Note that in the screenshot, the ismoving variable is updated after it is copied to wasmoving, so it is perfectly possible that the value of ismoving is different from the value of wasmoving by the time the condition is evaluated.
Your transformation of the code from the screenshot is inaccurate. You have changed the order of the operations.
C++ and Java, like most mainstream programming languages, are "imperative" languages. This means that programs consist of sequences of instructions that are performed one after another. When that code does:
boolean wasJumping = isJumping;
isJumping = ...someCalculation...;
That first sets the value of wasJumping to be the current value of isJumping, then changes the value of isJumping to something else. wasJumping doesn't change - it still has the old value that was taken from isJumping.
If you come from a mathematical background this can be confusing. I find it helps to read "wasJumping = isJumping" as "wasJumping becomes equal to isJumping", not "wasJumping equals isJumping". The former reinforces that it's describes a change in a variable, rather than describing a permanent relationship between two values.

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}