0

I try to help people learn to code in C++ and I received an answer for an easy task to write a code that gets three numbers as input and outputs a sum of them. I received a wrong-written code with no return statement which... suprisingly works. It prints a good answer to the console, which (as far as know) shouldn't happen without return. I know it is written wrong and I will reply how it should be done but I want to be precise and include an answer why it worked. Here is the code:

#include <iostream>

using namespace std;

int add ()
{
    int a,b,c, result;
    cin >> a;
    cin >> b;
    cin >> c;
    result=a+b+c;
}

int main()
{
    cout << add();

    return 0;
}

I would be grateful for an answer.

Pu6
  • 41
  • 5
  • 5
    Your program has _undefined behavior_, that it's seemingly working well, doesn't mean anything. – πάντα ῥεῖ Oct 06 '22 at 10:38
  • 1
    Undefined Behaviour is undefined. Anything can happen, including "doing what the programmer wanted program to do, but coded it wrongly" – Yksisarvinen Oct 06 '22 at 10:39
  • 2
    This is just a case of bad luck. There are no pixies in the machine that insert an obviously wrong value when a program misbehaves. – molbdnilo Oct 06 '22 at 10:51
  • Sometimes [when demons fly out of everyone's noses](http://www.catb.org/jargon/html/N/nasal-demons.html) they end up flying in the same direction that everyone's looking. – Sam Varshavchik Oct 06 '22 at 11:00
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Oct 06 '22 at 11:12
  • With the right compiler flags, this should give you a warning at compile-time, and then (if you enable sanitizers) an error at runtime. https://gcc.godbolt.org/z/4Ybo48Krv – HolyBlackCat Oct 06 '22 at 11:13
  • *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash"* – Jason Oct 06 '22 at 11:16

1 Answers1

-2

In some smart compilers it can run the code. but warning will be still there that function is expected to return integer but it is not returning anything. but in environment like visual studio it will give the error and program will not be build.

  • It is [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub), plain and simple. Has nothing to do with some compilers being "smart". – Jesper Juhl Oct 06 '22 at 11:14
  • Unfortunaetly not true. Either Code::Blocks or VSCode runs the code, although it throws a warning. – Pu6 Oct 06 '22 at 11:14
  • @Pu6 *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash"* – Jason Oct 06 '22 at 11:16
  • You sure this is an intentional compiler extension, rather than plain UB? – HolyBlackCat Oct 06 '22 at 11:17