Amit Ray
Amit Ray

Reputation: 3485

C++ code Stopped Working Error using cout inside function

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.

Upvotes: 0

Views: 130

Answers (1)

walnut
walnut

Reputation: 22152

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.

Upvotes: 4

Related Questions