cultered_man's blog

By cultered_man, history, 3 years ago, In English

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?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

a.size() — 2 is undefined when a.size() is 1.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    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.

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I thought it depends on compiler and machine that it will be either $$$2^{32} - 1$$$, $$$2^{64} - 1$$$ or simply UB.

      • »
        »
        »
        »
        3 years ago, # ^ |
          Vote: I like it +1 Vote: I do not like it

        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

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

unsigned to signed conversion is undefined behaviour when value do not fit into signed type