Hello programmers,
Recently, I have come across the unexpected behaviour in the code snippet below (loop is running infinitely many times)
#pragma GCC optimize("O3,unroll-loops")
#include<iostream>
using namespace std;
void yes() {cout << "YES\n";}
void no() {cout << "NO\n";}
bool contains() {
int n = 5;
while(n--) {
cout << "The value of n : " << n << endl;
}
}
int main() {
if(contains()) yes();
else no();
return 0;
}
And on removing the\#pragma GCC optimize("O3,unroll-loops")
from the above snippet. The code is showing the correct behaviour. Otherwise If I keep any return statement such as return true
or return false
inside the function contains()
, It is showing correct behaviour.
So, Out of my curiosity, I have some questions.
- As it is a warning warning: no return statement in function returning non-void [-Wreturn-type]
Can it change the behaviour of the code ? Why ?
- what does \#pragma GCC optimize("O3,unroll-loops")
do in general ?
- Is it safe to keep in my cp template ?
- Is it a good practice ?
Any help is greatly appreciated. Thanks in advance :)
@random_76
I think it's a UB in C++. With some compiler optimization directives, the compiler tries to do more stuff, and then it goes wrong. You need to study the implementation of the compiler to find the actual reason why. However it's not that important in my mind because it just shouldn't exist in any code.
Thank you :) It was found in my template. I haven't noticed it before until I get wrong submission and debugging it
They meant that the undefined behaviour should not be present in the code, rather than the pragma. The undefined behaviour in this case is what the warning tells you. Regardless of whether you had the pragma or not, when the compiler sees an undefined behaviour, it is free to do whatever it wants (and usually it goes with the easier/more optimized choice — sometimes even removing all code that depends on that undefined behaviour). To fix the issue, just make the function return some boolean and it should go away.
Waste of a blog. If you had spent 1 minute googling, you would have found an in-depth blog that marked your exact problem, but you chose to make a song and dance about it.
As the author of that blog, I don't see where this specific undefined behaviour (which is the actual problem with the code) is discussed in the blog or the comments.
However, it's always a nice thing to know more about the things you're using, so reading that blog will definitely help for the future.
Thank you nor for writing the blog.
Thank you for tagging the link of that blog. Will read that.