0

I wrote an int function without the return statement, but it still works, the code prints 4. Why?

#include <iostream>
#include<cstdlib>

using namespace std;

int quadrato1(int a)
{
    a = a * a;
}

int main()
{
    int x = 2;
    int y = quadrato1(x);
    cout << y << endl;
    system("pause");
    return 0;
}
  • [*Undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). – Some programmer dude May 19 '20 at 10:49
  • Make sure to search first. I used “c function return value without return statement”. – user2864740 May 19 '20 at 10:49
  • @user2864740 also if the result is right, my code is wrong because it is mandatory to write the return? – Federica Guidotti May 19 '20 at 10:51
  • To avoid Undefined Behavior (and thus to avoid the code being "wrong"), it is indeed mandatory.. some of the answers in the linked question explain this in (much) detail. – user2864740 May 19 '20 at 10:53
  • @user2864740 can i enable any warning message when there is not the return? – Federica Guidotti May 19 '20 at 10:57
  • Absolutely. Depends on compiler. [`-Wall -Wextra -Wpedantic`](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html) is generally a good starting place for GCC or Clang. Adjust to preferences. MSVC++ uses /W:number or some such? I don't use it.. – user2864740 May 19 '20 at 11:00

0 Answers0