Why doesn't the if else statement work? Please help...

YESH.CPP

Dani AI

Generated

Thread: issue with an if/else in YESH.CPP. 's suggestion to break complex logic into named variables is sound; the compiler evaluates Boolean expressions exactly, so surprising results almost always come from a small set of coding mistakes or type/initialization issues (see if statement - cppreference).

Common causes and quick checks:

  • Accidental assignment: if (x = 5) assigns 5 then tests it; use == for comparison.
  • Stray semicolon: if (cond); { ... } makes the block run unconditionally.
  • Missing braces or nested if/else ambiguity can attach else to the wrong if.
  • C-string vs std::string: == on char* compares addresses, not contents.
  • Uninitialized variables yield undefined behavior; initialize everything.
  • Implicit conversions (signed/unsigned, pointer/integer) can flip logic; add explicit casts or parenthesis.
  • Complex expressions: use parentheses or break into named bool variables for clarity.
  • Separate if vs else if: use else if when branches must be exclusive.

Practical debugging checklist: compile with warnings enabled (-Wall -Wextra), inspect values with a debugger or cerr, and add asserts for invariants. A small pattern that improves readability is to compute subconditions first and then make the decision:

bool condA = (x == 5);
bool condB = (ptr != nullptr && ptr->value > 0);

if (condA && condB) {
    // both true
} else if (condA) {
    // only A
} else {
    // neither
}

These steps make subtle bugs easier to spot and connect directly to 's advice about comparing one condition at a time.

Recommended Answers

All 2 Replies

deleted post

Creating such if-else logics is tricky. Remember you're talking to a compiler through C++, not another person. The compiler will not be able to generate the correct true or false you want from your conditions.

I suggest you approach the problem a different way, perhaps through a variable which you then compare one at a time( it's not a lot of code if you do it the smart way )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.