Why I am I getting a infinite loop for the below code
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ar array
#define nl '\n'
void solve(){
vector<int> a(1);
for (int i=a.size()-2;i>=0;i--){
cout<<i<<nl;
}
}
int32_t main(){
int tt{1};
for(int i=1;i<=tt;++i){
solve();
cout<<nl;
}
}
It is working fine with other online compilers could someone please help me on this. Am I missing something?
a.size() — 2 is undefined when a.size() is 1.
To play a devil's advocate
(oh no, have I really compared the C++ core team with the devil? Terribly sorry, I didn't mean to insult Lucifer):a.size() - 2
itself is perfectly defined and equals $$$2^{64} - 1$$$ in this case [on a x86-64 machine], but when it's shrunk to a 32-bit integer, stuff breaks down.I thought it depends on compiler and machine that it will be either $$$2^{32} - 1$$$, $$$2^{64} - 1$$$ or simply UB.
Unsigned types wraps according to stadart. Size depends on compiler, so 2^32 — 1 on 32-bit compilers and 2^64 — 1 on 64-bit compilers
unsigned to signed conversion is undefined behaviour when value do not fit into signed type