C++ code Stopped Working Error using cout inside function - c++

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.

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.

Related

Why "using namespace std;" gives different result when dealing with doubles in C++?

Today, I was trying to answer this post (regarding checking whether a triangle can be constructed), when I encountered a weird result.
With the test of 15.15 35.77 129.07, this piece of code:
#include <iostream>
using namespace std;
const double e = 0.000001;
void f(double a, double b, double c)
{
if (abs(180 - (a+b+c)) > e) {cout << "test"; }
}
int main()
{
double a,b,c; cin >> a >> b >> c;
f(a,b,c);
}
prints test as normal, while this:
#include <iostream>
const double e = 0.000001;
void f(double a, double b, double c)
{
if (abs(180 - (a+b+c)) > e) {std::cout << "test"; }
}
int main()
{
double a,b,c; std::cin >> a >> b >> c;
f(a,b,c);
}
does not. The only difference is the using namespace std; line (and when I added using namespace std; to the second piece of code, as expected, it ran normally).
I've read a lot of post regarding using namespace std; over time:
Using Namespace std
Why is "using namespace std;" considered bad practice?
...
but it seems that the only things using namespace std; do is cut some corners, in exchange of occasional conflicts of name of classes/variables/namespaces (the point that is brought up most when debating about whether to use it).
I did find 1 relevant post : Why does g++ (4.6 and 4.7) promote the result of this division to a double? Can I stop it? , but I didn't find anymore info elsewhere.
So what I'm I missing here?
-- Some machine info:
Windows 10, 64 bit
Code::Blocks 20.03
gcc/g++ 6.3.0
You do have a name conflict: int abs(int) versus double std::abs(double).
With using namespace std;, abs(180 - (a+b+c)) finds both and std::abs is a better match.
Without using namespace std;, abs(180 - (a+b+c)) only finds the former and a conversion to int is necessary, hence the observed behaviour.
What you really want is:
#include <iostream>
const double e = 0.000001;
void f(double a, double b, double c)
{
if (std::abs(180 - (a+b+c)) > e) {std::cout << "test"; }
}
int main()
{
double a,b,c; std::cin >> a >> b >> c;
f(a,b,c);
}
That's because you haven't added std:: to abs(), thus compiler doesn't really know what function it is, ergo UB. It most likely has found and used C version of function, which is made for int arguments.

Subroutine, without using pow, and with parameter and return

i don't understand what is wrong with my code it needs to have parameters and return, in c++
#include <bits/stdc++.h>
int p(int,int);
int main() {
int a,b,c;
scanf("%d",&a);
scanf("%d",&b);
printf("%d\n",c);
return 0;
}
int p(int a,int b){
int t,i,c=1;
for(i=1;i<=b;i++){
t=a;
c=c*t;
return t;
}
}
here's the input:
2
4
the output:
16
I expect you meant to write this code
int p(int a,int b){
int t,i,c=1;
for(i=1;i<=b;i++){
t=a;
c=c*t;
}
return t;
}
In your version the return statement is inside the for loop.
And as has been pointed out, you probably meant this
printf("%d\n",p(a,b));
instead of this
printf("%d\n",c);

Are C++ function declarations optional?

I just noticed something when creating functions. In the code:
#include <iostream>
using namespace std;
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
it will work because the function being called is on top of the caller, but if I put the function add() below the calling function in main() it won't work.
#include <iostream>
using namespace std;
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
and the compiler will tell me that the identifier add() cannot be found.
so why do we declare functions anyway? like this:
#include <iostream>
using namespace std;
int add(int a, int b = 20);
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b)
{
int r;
r = a + b;
return (r);
}
A definition is implicitly a declaration. And a declaration must come ahead of the use.
All functions need to be declared before they are used.
You can do that by either (1) writing a declaration, or (2) writing a definition.
Relying solely on (2) can be tempting but then you are bound to order your program in a particular way, and is occasionally impossible. For example, the following will not compile unless the comment is removed.
//void bar(int);
void foo(int n)
{
if (!n){
bar(n);
}
}
void bar(int n)
if (n){
foo(n);
}
}
int main()
{
foo(1);
}
No.
If the function definition appears before the function call, then prototype is not mandatory. Otherwise function prototype is necessary to let compiler know how to respond to a function when it is called.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
if the function definition appears after the function call then prototype is mandatory. because it tells the compiler to how to respond the function when it is called.
check the following example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int, int); // function prototype
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
and if the function definition is made before the function call then it is not mandatory to declare function prototype.
consider example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}

Obtain variables in function from other function C++

I am trying to pass a variable from one function to another. I have tried this approach but it is not working for me:
int c (){
int x1,x2,y2,y1;
system("cls");
cout<<"Insert Value"<<endl
cin>>x1;
return x1;
}
int cd()
{
int a;
a=c();
cout<<"X1: "<<a;
}
Any help is appreciated. Thanks!
There are a few problems with your code.
First of all you are missing a semicolon after the cout statement in your c() function.
Also you have indicated that function cd() should return an int but you are not returning anything.
Lastly, these function will not begin execution unless you call them explicitly.
Try this:
#include <iostream>
using namespace std;
int c (){
int x1,x2,y2,y1;
cout<<"Insert Value"<<endl;
cin>>x1;
return x1;
}
int cd(){
int a;
a=c();
cout<<"X1: "<<a;
return a;
}
int main()
{
int x=cd(); //call the function to create the side effects
return 0;
}

object.function().function().function()....... how does this work?

i have a problem understanding how c++ syntax works.
#include<iostream>
using namespace std;
class Accumulator{
private:
int value;
public:
Accumulator(int value){this->value=value;}
Accumulator& add(int n){value+=n;}
int get(){return value;};
};
int main(int argc, char* argv[]){
Accumulator acc(10);
acc.add(5).add(6).add(7); //<-----how does this work?????
cout<<acc.get();
return 0;
}
this line: acc.add(5).add(6).add(7);
does it work left to right or the other way
something like acc.add(5) first and then do add(6)
i dont get it.
result is supposed to be 28.
thanks in advance.
edit:
weird, this code gets compiled successfully without any errors on g++.
i got this code from some non-english college c++ textbook. english is not my first language.
2nd edit: i now get the desired warnings after using -Wall option.
Your code doesn't compile, but if it did, it would work left to right. Add returns a reference to an Accumulator (it doesn't have a return value in your code, but it should probably return *this) so after you call
acc.add(5)
the return value is a reference to acc, which you can call add on again.
Here is a modified example with mult added that shows order of operations:
#include <iostream>
using namespace std;
class Accumulator{
private:
int value;
public:
Accumulator(int value){ this->value = value; }
Accumulator& add(int n){ value += n; return *this; }
Accumulator& mult(int n){ value *= n; return *this; }
int get(){ return value; };
};
int main(int argc, char* argv[]){
Accumulator acc(10);
acc.add(5).add(6).mult(7);
cout << acc.get();
return 0;
}
If it was right to left, the result would be 81, but it is left to right and the result is 147.
This is called Method chaining and is commonly seen in Fluent Interface pattern.
Each method call (acc.add(5)) returns a reference or pointer upon which successive method calls (.add(7)) can operate on.