c++ when reference variable's value change? [duplicate] - c++

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))

Related

Why the compiler does not raise an error when not passing address of array element? [duplicate]

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.)

Why address gotten from the pointer is always the same? [duplicate]

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.

Why does this function in C++ work, but only if printed to stdout? [duplicate]

This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 3 years ago.
I'm trying to understand how references/pointers/dereferencing works in c++. Please see below for some example code :
#include <iostream>
#include <cstdio>
int& plusThree(int num)
{
int threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}
int main()
{
int three = plusThree(0);
std::cout << "three is " << three << "\n";
return 0;
}
The function plusThree() shouldn't work, and if you run the code, it doesn't. It'll return three is 0. However, if you uncomment either of the lines which prints threeMore, main will now print three is 3...
So my questions are as follows:
Why does the function plusThree() not work? is it because int& means it should return an integer reference, but return threeMore is returning an int?
Why does the function plusThree() now work, if one of std::cout or printf is uncommented?
Thanks!
As #Retired Ninja mentioned, returning a reference to a local variable from a function has undefined behavior...
The int threeMore; should be defined outside the function, or it must be returned by value not a reference.
You must change plusThree's implementation, or the int threeMore; variable:
int threeMore;
Return by reference:
int threeMore = 0;
int& plusThree(int num)
{
threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}
Return by value:
int plusThree(int num)
{
int threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}

Difference between call by address(pointer) and call by reference [duplicate]

This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
Can you tell me the difference between the source 1 and 2?
The book says the first one is call by address(pointer) and the second one is call by reference, but i don't exactly get those two sources.
Please explain those sources to me please, thank you in advance.
1.
#include <iostream>
using namespace std;
void absolute(int *a);
void main()
{
int a = -10;
cout << "Value a before calling the main function = " << a << endl;
absolute(&a);
cout << "Value a after calling the main function = " << a << endl;
}
void absolute(int *a)
{
if (*a < 0)
*a = -*a;
}
2.
#include <iostream>
using namespace std;
void absolute(int &a);
void main()
{
int a = -10;
cout << "Value a before calling the main function" << a << endl;
absolute(a);
cout << "Value a after calling the main function" << a << endl;
}
void absolute(int &a)
{
if (a < 0)
a = -a;
}
In terms of what happens at the CPU level, pointers and references are exactly the same. The difference lies in the compiler, it won't let you do a delete on a reference (and there's less typing)
So in your code both functions do the same thing.

Calculating modulus in a function gives different answer from using % operator directly [duplicate]

This question already has answers here:
Modulo operator with negative values [duplicate]
(3 answers)
Closed 9 years ago.
my_mod.cpp:
#include <iostream>
using namespace std;
unsigned int my_mod(int a, unsigned int b)
{
int result;
cout << "\ta\t=\t" << a << endl;
cout << "\tb\t=\t" << b << endl;
cout << "\ta%b\t=\t" << a%b << endl;
result = a%b;
if (result < 0) {result += b;}
return result;
}
int main()
{
cout << "-1%5 = " << -1%5 << endl;
cout << "my_mod(-1,5) = " << my_mod(-1,5) << endl;
return 0;
}
compiled via:
g++ ./my_mod.cpp
results in:
-1%5 = -1
a = -1
b = 5
a%b = 0
my_mod(-1,5) = 0
What the actual hell is happening here I just can't understand what possibly could go on?! This can't be due to the global scope, right?!
I mean it is exactly the same %-expression ... how can they yield 0 and -1?! (Instead of the desired 4, by the way.)
Please, if anybody can, explain this to me ... it just took me days to narrow down an error in a wider context to this. Seriously, I'm about to cry.
How can I have my (global) own modulus returning 4 in the example above??
It's because you're using an unsigned int, the signed int (-1) gets promoted to -1 % UINT_MAX so your operation becomes (-1 % UINT_MAX) % 5 = 0 (thanks to jrok for this more detailed reason)
try
cout << "\ta%b\t=\t" << a%(int)b << endl;
result = a%(int)b;
with function signature of: int my_mod(int a, unsigned int b)
Or just use a function signature of: int my_mod(int a, int b)