BIZZARRREEE! Can anyone explain this mind-boggling goggling bug?

Hey guys,
So I was solving the 3-sum problem recently where we have to find all distinct triplets which sum to 0.
While solving, I encountered a very peculiar yet inextricable bug. Can anyone help me out in figuring this out? this is making me sleep deprived!! :/
I'm attaching two sets of code below.
try running both of them for the test case : [] (empty vector)

For those who feel very lazy to open an ide and run this code. I'll briefly explain what I'm on about:
For the above mentioned test case compilers enters into the for-loop even when the condition is not satisfying i.e.

for(int i=0;i<nums.size()-2;i++){
} // compiler enters this for-loop

but when I do this:

int len = nums.size();
for(int i=0;i<len-2;i++){
} // compiler doesn't enter into this code

CAN SOMEONE PLEASE TELL ME WHY THIS IS HAPPENING???????

I'm attaching the complete code for reference with print statements for those who are intrigued and have ample time and generosity to debug this so that I can get my REM sleep :/

CODE ::

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        int len = nums.size();
        
        sort(nums.begin(),nums.end()); 
        for(int i=0;i<nums.size();i++){
            cout<<nums[i]<<" ";
        }
        int prevI = INT_MIN;
        cout<<len<<endl;
        cout<<nums.size()<<endl;
        //cout<<nums[0];
        for(int i=0;i<nums.size()-2;i++){
            cout<<"it is coming here"<<endl;
            int l = i+1;
            int r = nums.size()-1;
            if(prevI == nums[i]){
                continue;
            }
            prevI = nums[i];
            int prevL = INT_MIN;
            while(l<r){
                int sum = nums[i] + nums[l] + nums[r];
                if(sum>0){
                    r--;
                }
                else if (sum<0){
                    l++;
                }
                else{
                    if(prevL == nums[l]){
                        l++;
                        continue;
                    }
                    ans.push_back({nums[i] , nums[l] , nums[r]});
                    prevL = nums[l];
                    l++;
                    r--;  
                }
                
                // [-4,-1,-1,1,1]
            }
        }
        return ans;     
    }
};

Expecting a solution soon :/

Comments (2)