Why is the position of the or-argument relevant?
Hello, I wrote a program in C++ that reads words from the command line and then outputs them from shortest to longest. The program works. However, there's a problem I don't understand. In the "next" function of the "array" class, swapping the if conditions (result == nullptr) and (y[i] < *result) displays a different result: only the shortest word. Why is this?
#include <iostream> #include <cstdlib> #include <string> using namespace std; template <typename T, typename K> class Paar { private: T ersten; K zweiten; public: Paar() {} Paar(T a, K b) : ersten(a), zweiten(b) {} T getErsten() const { return ersten; } K getZweiten() const { return zweiten; } bool operator ==(const Paar& a) const{ return (ersten == a.ersten); } bool operator <(const Paar& b) const{ return (ersten < b.ersten); } }; template <typename T1> class Array { private: T1* y; int size; int occupied; public: Array(int x) : y(new T1[x]), size(x), occupied(0) {} bool dazu(const T1& x) { if (occupied < size) { y[occupied] = x; occupied++; return true; } return false; } T1* keinste() { int j = 0; if (occupied == 0) { return nullptr; } for (int i = 1; i < occupied; i++) { if (y[i] < y[j]) { j = i; } } return &y[j]; } T1* naechstes(const T1& a) { T1 * ergebnis = nullptr; if (occupied == 0) { return nullptr; } for (int i = 0; i < size; i++) { if ((a < y[i]) && ((ergebnis == nullptr) || (y[i] < *ergebnis))) { ergebnis = &y[i]; } } /* if ((*ergebnis < a) || (*ergebnis == a)) { return nullptr; } */ return ergebnis; } ~Array() { delete[] y; } }; int main(int argc, const char* argv[]) { typedef Paar<string, int> PaarType; Array<PaarType> a(argc - 1); for (int i = 1; i < argc; i++) { PaarType b(argv[i], i); a.dazu(b); } for (PaarType* c = a.keinste(); c != nullptr; c = a.naechstes(*c)) { cout << "erster Wert: " << c->getErsten() << " zweiter Wert: " << c->getZweiten() << endl; } return 0; }
The position of the operator or operator in the If condition is relevant since the evaluation of the condition takes place from left to right and the expression is terminated as soon as the result is fixed.
In the original code, the condition
. Here is first
evaluated. If this condition
the program does not go further and the loop jumps to the next iteration. This means that the word is skipped when it is not smaller than
is.
However, if you change the position of the or operator and the condition
use, will be first
evaluated. If
However,
is the dereference operator
on
which leads to undefined behavior. This behavior can differ from system to system. It is therefore recommended not to carry out undefined operations.
The original position of or operator is correct as it ensures that the condition
first checked and then
. This ensures that
not referenced when it
is.
I’ve never really thought about it
kA ob’s right, was chatgpt