Sorting int's in C++, when variables are allocated next to each others in memory?

So i came up with simple idea of sorting separate int variables, which are declared next to each other. For example:

int a=2, b=6, c=3, d=5;
sort(&a, &d+1);
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;

Before saying me that I should not use above technique, because of multiple reasons, I would like to say that it is useful in competitive programming when you have to type short and possibly clean code. Unfortunately I fell somehow of bad when using above code, and I would like to know when C++ allocate variables in neighbour cells, and what is probability or guaranty that it is going to happen.


Solution 1:

I would like to know when C++ allocate variables in neighbour cells

The standard never explicitly guarantees this.

It also doesn't matter much since if you iterate past the bounds of the object (beyond one past the object) then the behaviour of the program is undefined.


Where the standard does guarantee that objects are adjacent is arrays. Furthermore, you can use pointers to iterate over the elements of arrays. Hence, your example can be correctly written like this:

int arr[] {2, 6, 3, 5};
std::sort(std::begin(arr), std::end(arr));
for (int a : arr) {
    std::cout << a << ' ';
}
std::cout << '\n';

Solution 2:

There is no guarantee that your 4 variables will be next to each others in memory. It will depends of so many things that you can't predict it.

But with an array, it is always the case :

int ints[] = {2, 6, 3, 5};
sort(ints, ints + 4);