Unexpected Behaviour of the code

Правка en1, от random_76, 2023-06-20 22:59:54

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

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский random_76 2023-06-20 22:59:54 1238 Initial revision (published)