1

Add of std::valarray got different sizes with different operand orders.

Code is as the following:

#include <iostream>
#include <valarray>
using namespace std;

int main() {
    std::valarray<float> v0{3.f, 0.f};
    std::valarray<float> v1{0.f};
    std::valarray<float> v2 = v0 + v1;
    std::valarray<float> v3 = v1 + v0;
    cout << v2.size() << endl; // 2
    cout << v3.size() << endl; // 1
}

Compilers:

g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
clang version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)
chaosink
  • 1,329
  • 13
  • 27
  • 1
    Attempts to perform arithmetic on two `valarray`s of different sizes exhibit undefined behavior. – Igor Tandetnik May 31 '20 at 02:58
  • Fine... But I think preserving the max size and setting the last elements to 0 is more natural. – chaosink May 31 '20 at 03:07
  • @chaosink What matters is what the standard says, not what you'd like it to say. The rationale for why this restriction exists might be performance. – bitmask May 31 '20 at 03:10
  • See https://en.cppreference.com/w/cpp/numeric/valarray/operator_arith3 – bitmask May 31 '20 at 03:12
  • @bitmask Give me a chance to modify the standard! – chaosink May 31 '20 at 03:12
  • @chaosink Have at it. The way I understand it, everyone is free to suggest papers to the standardization committee. But it usually takes many years until they are incorporated. – bitmask May 31 '20 at 03:14
  • @bitmask This makes me want to implement my own valarray... – chaosink May 31 '20 at 03:14
  • @chaosink if you need that functionality, just wrap the existing valarray and insert appropriate checks in all operators. – bitmask May 31 '20 at 03:15

1 Answers1

1

operator+() does not perfom concatenation of two std::valarray<float> objects,

std::valarray<float> v2 = v0 + v1;

Here, since v1 is of size 1, it will add the only value in v1 to both the elements in v0, hence size stays 2.

std::valarray<float> v2 = v1 + v0;

But here, v1 is of size 1, it will add the first element 3.f to the only element in v1 and second value of v0 is ignored. This is what usually happens, but nevertheless the behaviour of binary operations on two valarrays are undefined.

Amal K
  • 4,359
  • 2
  • 22
  • 44