0

I am trying to create a new uint24_t type for use on my embedded device. All functionality appears to work except when I use the type in an output stream.

I thought this might be an issue with not overloading the << operator however I tried this with friend std::ostream& operator <<(std::ostream &out, const uint24_t b) { out << (uint32_t) b.val; return out; } and it still yielded the same results

#include <iostream>

struct uint24_t
{
private:
    uint32_t val;

public:
    uint24_t() {}

    uint24_t(const uint32_t& a) {
        val = a;
        val &= 0x00FFFFFF;
    }

    uint24_t(const uint24_t& a) {
        val = a.val;
    }

    operator uint32_t() const {
        return val;
    }

    uint24_t operator++(int) {
        uint24_t temp = val;
        val = val + 1;
        val &= 0x00FFFFFF;
        return temp;
    }
};

int main()
{
    uint24_t var;

    // Test post incrementor in ostream for uint24_t
    var = 0;
    std::cout << std::hex << var++ << " " << var << std::endl; // Outputs 0 0  (should be 0 1)
    std::cout << std::hex << var << std::endl;                    // Outputs expected 1

    // Test post incrementor in isolation for uint24_t
    var = 0;
    uint32_t temp = (var++) + (var);
    std::cout << std::hex << temp << std::endl; // Outputs expected 1
}

I expect the output of std::cout << std::hex << uint24++ << " " << uint24 << std::endl; to be 0 1 however I actually get 0 0

Xenoamor
  • 11
  • 1
  • 3
    Probably because of undefined behavior. More on the subject in [this SO post](https://stackoverflow.com/questions/3986361/behavior-of-post-increment-in-cout). – Ron Aug 22 '19 at 12:42
  • 1
    "`// Outputs 0 0 (should be 0 1)`" You are under the false assumption that operands are evaluated from left to right. – François Andrieux Aug 22 '19 at 12:47
  • 1
    Thanks, this is definitely what is going on. Clang produces the "expected" output. Shame GCC doesn't pick up on it with `-Wsequence-point` – Xenoamor Aug 22 '19 at 13:02

0 Answers0