0

My Code doesnt work when I use cout inside a function but if I return the value and stream inside main function it works. My code which does not work is

#include <iostream>
#include <cstring>
using namespace std;
int add(int a,int b){
  int c = a+b;
  cout<<c<<endl;
}
string add(string m,string n){
  string c = m+" "+n;
  cout<<c<<endl;
}
int main(){
    string x ="amit";
    string y ="kumar";
    add(x,y);//adding string
    add(5,58);//adding numbers
}

But when I return the value it works fine

#include <iostream>
#include <cstring>
using namespace std;

int add(int a,int b){
  int c = a+b;
  cout<<c<<endl;
}
string add(string m,string n){
  string c = m+" "+n;
  return c;
}
int main(){
    string x ="amit";
    string y ="kumar";
    string z = add(x,y);

    cout<<z<<endl;
    add(5,58);//adding numbers
}

I am using Codeblocks for my programming. Why is this abrupt behaviour. What am I doing wrong here.

Amit Ray
  • 3,445
  • 2
  • 19
  • 35
  • The program is just existing, closing the console, and you're unable to see the output. Run from the command shell. – Ajay Jan 30 '20 at 06:34
  • 1
    https://stackoverflow.com/questions/11096027/function-returning-stdstring-crashes-without-return-statement-unlike-a-functi – M.M Jan 30 '20 at 06:40

1 Answers1

4

Both your programs have undefined behavior.

string add(string m,string n) and int add(int a,int b) have declared non-void return types. But the functions flows of the end without a return statement that returns anything. That causes undefined behavior.

If you add a proper return statement or change the declared return type to void it will work as expected in both programs.

If you haven't yet, enable additional warnings in your compiler. It should have warned you about this problem. If it did warn you, then please never ignore warnings. Fix all of them.


Also note that you need to #include<string>, not #include<cstring>, to use std::string.

walnut
  • 21,629
  • 4
  • 23
  • 59
  • Why the same is not happening in case of int why only string? – Amit Ray Jan 30 '20 at 06:38
  • @AmitRay It is *undefined behavior*. You have no guarantee that anything specific will happen. I have updated my answer to clarify that both programs have undefined behavior. – walnut Jan 30 '20 at 06:41