Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int * add(int *, int *);
int add(int, int);
void main() {
int a, b, sum, *z;
cout << "enter the value of a & b";
cin >> a >> b;
z = add(&a, &b);
sum = add(a, b);
cout << "\nthe sum is: " << sum << endl;
cout << "the sum is :" << *z << endl; getch();
}
//.....calling with value.....
int add(int a, int b) {
int s;
s = a + b;
return s;
}
//......calling with address.......
int *add(int *a, int*b) {
int r;
r = *a + *b;
return &r;
}
Why does it give the wrong answer:
output........ a=70 b=80 the sum with value is: 150 the sum with address is :1208
...but when I give the program as:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int * add(int *, int *);
int add(int, int);
void main() {
int a, b, sum, *z;
cout << "enter the value of a & b";
cin >> a >> b;
sum = add(a, b);
cout << "\nthe sum is: " << sum << endl;
z = add(&a, &b);
cout << "the sum is :" << *z << endl;
getch();
}
//.....calling with value.....
int add(int a, int b) {
int s;
s = a + b;
return s;
}
//......calling with address.......
int *add(int *a, int*b) {
int r;
r = *a + *b;
return &r;
}
It gives right answer.
output..... a=70 b=80 the sum with value is:150 the sum with address is:150.
Why?
int *add(int *a,int *b)
{
int r; // r resides on stack
r=*a+*b;
return &r;
} // life time of r ends here.
You are returning the address of a local variable causing undefined behavior. Compiler should have warned about it.
When you return the address of r, in main, you have the address of a variable that is on the stack, in an area of stack that is currently "free". Using memory after it has been freed, whether it's "stale stack" or "stale heap" is "undefined behaviour"
In this case, any use of the location of r on the stack in the future will overwrite the value in r with some other "random" value. In this case, it looks like it may be the address of the function add (with int parameters).
I would also suggest that you use a more modern compiler (one that isn't old enough to legally apply for a driving license in most countries) and enable warnings. For example GCC (which is free software, so no cost) - it will give warnings for "returning address of local variable".
Related
This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 1 year ago.
I have the following code
# include <iostream>
using namespace std;
void show (int list[], int len) {
for (int i = 0; i < len; i++) {
cout << list[i] << " ";
}
cout << endl;
}
void swap (int* a, int* b) {
cout << *a << ' ' << *b << endl;
int c = *a;
*a = *b;
*b = c;
cout << *a << ' ' << *b << endl;
}
void aFunction (int list[], int len) {
cout << "From aFunction ";
show(list, len);
swap(list[0], list[1]);
cout << "From aFunction ";
show(list, len);
}
int main() {
int list[] = {6, 4};
int len = sizeof(list)/sizeof(int);
aFunction(list, len);
return 0;
}
When I compile and run this I do not get any errors and I receive the output as
From aFunction 6 4
From aFunction 4 6
But when I change the following line in aFunction
swap(list[0], list[1]);
to
swap(&list[0], &list[1]);
it still compiles and give me the following output
From aFunction 6 4
6 4
4 6
From aFunction 4 6
What is going on? My initial thought was swap(list[0], list[1]) is right since arrays decay to pointers when passed to a function so we are essentially passing pointers to swap but then the cout in swap is not printed, which leads me to believe swap(&list[0], &list[1]) is right. If the latter is right, why the compiler does not raise any error for the first and why the cout in swap does not execute? Which one is right? What's going on????? I am compiling this program using g++ weird.cpp on a MacBook Pro. I would be really grateful for an explanation.
You're calling std::swap, not your own swap function.
std::swap takes two reference arguments of any matching type.
(This is why, IMHO, using namespace std; can be a bad idea. I prefer to qualify names with std:: explicitly.)
This question already has answers here:
Order of evaluation of arguments using std::cout
(5 answers)
Closed 2 years ago.
using namespace std;
int foo1(int &n);
int foo2(int n);
int main() {
int n1, n2;
cout << foo1(n1) << n1 << foo2(n2) << endl;
}
int foo1(int &n) {
n = 3;
return 1;
}
int foo2(int n) {
return 2;
}
and I get output 1 (trash val) 2.
Why n1's value is not modified? foo1() is worked faster than cout << n1;?
When reference var's value modified?
This
cout << foo1(n1)<<n1<<foo2(n2)<<2ndl;
actually resolves to
operator<<(operator<<(operator<<(operator<<(cout, foo(n1)), n1), foo2(n2)), endl);
The order of arguments evaluation is not defined by the standard. It's an implementation dependent. So here
operator<<(operator<<(cout, foo(n1)), n1)
either can be evaluated first. And in your case it appears n1 took the first place and then operator<<(cout, foo(n1))
This question already has answers here:
How to print function pointers with cout?
(7 answers)
Closed 2 years ago.
I am a bit confused now. So, if i write the following code:
int x = 5;
cout << &x << endl;
compile it and run, I'll get something like 0x920FC7D which is the normal hexadecimal value for memory locations. But when I compile and run the following code:
#include <iostream>
using namespace std;
void add(int a, int b){
cout << a + b << endl;
}
void subtract(int a, int b){
cout << a - b << endl;
}
void multiply(int a, int b){
cout << a * b << endl;
}
int main(){
void ( *operations[3] ) (int, int) = {add, subtract, multiply};
int length = sizeof(operations)/sizeof(operations[0]);
for(int i=0; i < length; ++i){
cout << operations[i] << endl;
}
return 1;
}
I always get:
1
1
1
It seems the address of pointer should also be hexadecimal value, but even if it's binary or just decimal, why it is always the same?
If you take a look at the overloads for the operator << with a std::ostream& as the left hand operand, you'll find that there are no overloads for pointers to functions as right hand operand.
But you are inserting function pointers. So, what is being inserted? Well, function pointers are implicitly convertible to bool, and there is an overload for bool. All are 1 because all of the converted values are true. This is because none of the function pointers were null which is the only function pointer that converts to false.
These are the requirements for my program. Code a program that will find the minimum, maximum, and sum of two integers and of three integers. Use 1 overloaded function for each of min, max, & sum. I have gotten most of it done, but dont know how to add an overload function. here is my code
#include <iostream>
using namespace std;
int main(){
int num1, num2;
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
cout<<"Sum of " << num1<< " and " <<num2<<" is: "<<(num1+num2)<<endl;
if (num1>num2)
{
cout << "The max is " << num1<< " and the min is " << num2<< endl;
}
else
{
cout<< num2 << " is the max, and " <<num1 <<" is the min"<<endl;
}
return 0;
}
The idea here is to separate the code into functions, and more specifically, to two different functions, with the same name, but with a different parameters (this means that this function has a different signature, and this is how the compiler distinguish one function to another!).
The code should look like that:
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
int max(int a, int b)
{
return (a > b) ? a : b;
}
int max(int a, int b, int c)
{
return max(a, max(b, c));
}
Notice the little "trick" (which is recommended), that I have used the 2-argument max in the 3-argument max, instead of re-implement the same logic twice. In this way, if you have a bug, you will have a bug in both, but if you fix it, it will be fixed in both at the same time. This is true for many other type of functions!
Also, denote the (expression) ? (value_1) : (value_2) which is a short version for if assignment, which can be used when assigning variables or when returning a value, and are in common use.
P.S you can make in such a way an overload for any number of arguments, and for any type that has the operator< (although it does contain a problem, if the arguments are not from the same type!), using:
template <typename T>
T max(T a, T b)
{
return (a > b) ? a : b;
}
template <typename T, typename... Ts>
T max(T a, Ts... others)
{
const T max_of_others = max(others...);
return (a > max_of_others) ? a : max_of_others;
}
int main()
{
std::cout << "max of 1-6 is: " << max(1, 6, 3, 4, 5, 2) << std::endl;
}
But it is an overkill here! (just good to know for the future!)
new to learning c++ and I was wanting to understand the program ive practiced. I have a section of code I want to understand but im kind of lost.
#include "stdafx.h";
#include <iostream>;
// getValueFromUser will read a value in from the user, and return it to the caller
int getValueFromUser()
{
std::cout << "Enter an integer: ";
int a;
std::cin >> a;
return a;
}
int main()
{
int x = getValueFromUser(); // first call to getValueFromUser
int y = getValueFromUser(); // second vall to getValueFromUser
std::cout << x << " + " << y << " = " << x + y << std::endl;
return 0;
}
Im just wanting to know how " int a " comes into play here. If someone could help it would be appreciated.
You declare an uninitialized variable of type int with identifier a:
int a;
The user provides a value to a.
std::cin >> a;
A copy is returned from the function:
return a;
Calls to the getValueFromUser() will create a temporary a,
assign it to user input, and return it each time.
In c++ you have to declare variable (providing the type and name) before it's first use.
std::cin has to put it's output somewhere and that's why you need this additional variable.