For example if I subtracted an array with size 3 from an array with size 2, it returns 3 no matter what is inside. Why is that?
Ex:
int a[2] = {1,2};
int b[3] = {999,999,999};
cout << a-b;
And the output is 3
For example if I subtracted an array with size 3 from an array with size 2, it returns 3 no matter what is inside. Why is that?
Ex:
int a[2] = {1,2};
int b[3] = {999,999,999};
cout << a-b;
And the output is 3
The first question here that, what is the subtraction of two arrays? If you are mentioning the subtraction of the elements that have the same indexes, you have to make sure that the array's size is equal. Then iterate through both arrays and subtract one to another using loop. The thing you want to achieve results in undefined behavior. You can alternatively use the overloaded '-' operator to subtract two array objects but it is a little bit complicated.
This simply happens, because your example does substract pointers of int, instead of the vector.
What happens is this:
&a[0] - &b[0]
I assume you try to achieve a vector substraction instead. One approach is to overload the operatror -
.
Have a look here, how operator overloading can be done: What are the basic rules and idioms for operator overloading?
it returns 3 no matter what is inside
No, it does not always return 3.
It depends on the compiler/linker/library/platform/many other factors.
For example, on my machine the g++ compiler and the MSVC get two different results. You should never make any assumptions and rely on this behavior.
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
{
int a[2] = {1, 2};
int b[3] = {999, 999, 999};
cout << a - b << endl;
cout << static_cast<void *>(a) << ' ' << static_cast<void *>(b) << endl;
}
{
int a[2] = {1, 2};
int middle_array[2] = {1, 2};
int b[3] = {999, 999, 999};
cout << a - b << endl;
cout << static_cast<void *>(a) << ' ' << static_cast<void *>(b) << endl;
}
return 0;
}
With G++
$g++ t3.cpp && ./a.exe
3
0xffffcc28 0xffffcc1c
5
0xffffcc14 0xffffcc00
With MSVC
cl t3.cpp && t3.exe
-6
00000012814FFB00 00000012814FFB18
-8
00000012814FFB08 00000012814FFB28
P.S. For the curious. These are test results of two different machines(g++):
4
0x7ffcdaa00640 0x7ffcdaa00630
8
0x7ffcdaa00620 0x7ffcdaa00600
-2
0x7ffd969a2904 0x7ffd969a290c
-4
0x7ffd969a28fc 0x7ffd969a290c