Cout behaving wierdly

Please help with this error.
My code: CodeChef: Practical coding for everyone
Problem: Chewing | CodeChef
I don’t know if this is an error in the codechef c++ compiler? Or did i mess up the ram while using pointers.
if i comment out line 21 ( cout<<“”; ) it gives a different answer than when it is uncommented. That line does absolutely nothing according to me.
What is up?

Fix the last of these warnings and try again :slight_smile:

[simon@simon-laptop][17:47:32]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling ras2004shaikh-ZCO13003.cpp
Executing command:
  g++ -std=c++17 ras2004shaikh-ZCO13003.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG    -fsanitize=undefined -ftrapv
ras2004shaikh-ZCO13003.cpp: In function ‘int main()’:
ras2004shaikh-ZCO13003.cpp:20:49: warning: conversion to ‘int’ from ‘long int’ may alter its value [-Wconversion]
         int fin_pos=(lb(&A[i+1],&A[fin_pos],K-a)-&A[0]);
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
ras2004shaikh-ZCO13003.cpp:17:9: warning: unused variable ‘fin_pos’ [-Wunused-variable]
     int fin_pos=N;
         ^~~~~~~
ras2004shaikh-ZCO13003.cpp:20:43: warning: ‘fin_pos’ may be used uninitialized in this function [-Wmaybe-uninitialized]
         int fin_pos=(lb(&A[i+1],&A[fin_pos],K-a)-&A[0]);
                                           ^
Successful
1 Like

Umm i don’t know. I just gave up yesterday made a few changes today and submitted. And for some reason it is working now?
Solution: 53087500 | CodeChef
But i don’t understand fin_pos is initialized as long as there is input N.

I needed to increase speed a bit so i made a few changes again.
My final solution:
Solution: 53088568 | CodeChef

But i still don’t get why my earlier code was behaving erratically.
I don’t see anything wrong that i did in the previous code.

  int fin_pos=(lb(&A[i+1],&A[fin_pos],K-a)-&A[0]); // Line 20

You were initialising the fin_pos declared at line 20 with itself (i.e. with the fin_pos declared at line 20), which is nonsense :slight_smile:

1 Like

ooooh. My bad. Thanks a lot. that int. So that’s what was causing trouble. so C++ kinda thought it was a local variable, got confused and started printing garbage values.

1 Like

Things like these are actually the main reason why I’m using D language for competitive programming instead of C++. In D language all variables and arrays are initialized by default, out of bounds array accesses are checked at runtime (but can be omitted in a release build), signed integers assume 2’s complement representation, etc. All of these convenience and safety features make it much less likely to accidentally introduce undefined behaviour in D code and waste time debugging it. And the nonsense initialization of a variable with itself is a compilation error.

1 Like