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

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.

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 is the sizeof() my double array[4] only 4? [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 5 years ago.
I am trying to write a loop which runs across all the elements in the array. I learned the concept here. I am facing some difficulty with its execution. I have been trying to debug and I have written the following function as part of that debugging process. The following is my code:
#include <iostream>
using namespace std;
struct Vmul {
double c[4][4];
};
double Vmulti(double a[4], double d[4]) {
cout << sizeof(a) << endl;
cout << sizeof(a[0]) << endl;
cout << sizeof(a)/ sizeof(a[0]) << endl;
return 0;
}
int main()
{
double r[4] = { 1,2,3,4 };
double q[4] = { 1,2,3,4 };
Vmulti(r, q);
return 0;
}
Output:
4
8
0
Press any key to continue . . .
I am unable to figure out why sizeof(a) return only 4? shouldn't it be 8*4? why isn't sizeof giving me the size and instead giving me the number of elements in the array?
An error message from a compiler can go a long way:
test.cpp:8:23: warning: sizeof on array function parameter will return size of 'double *' instead of 'double [4]'
[-Wsizeof-array-argument]
cout << sizeof(a) << endl;
^
test.cpp:7:22: note: declared here
double Vmulti(double a[4], double d[4]) {

Overloading a function in C++ [duplicate]

This question already has an answer here:
Using float gives "call to overloaded function is ambiguous" error [duplicate]
(1 answer)
Closed 6 years ago.
I'm learning C++ through Sololearn. I have a doubt about function overloading
this is the code
#include<iostream>
using namespace std;
void printSomething(int x) {
cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x) {
cout << "I'm printing a float " << x << endl;
}
int main() {
int a =3;
float b = 2.65;
printSomething(a);
printSomething(b);
return 0;
}
it gives output as
I'm printing an integer 3
I'm printing a float 2.65
but if I directly give argument when calling function
like this
#include<iostream>
using namespace std;
void printSomething(int x) {
cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x) {
cout << "I'm printing a float " << x << endl;
}
int main() {
printSomething(3);
printSomething(2.65);
return 0;
}
i get following error
..\Playground: In function 'int main()':
..\Playground:19:24: error: call of overloaded 'printSomething(double)' is ambiguous
printSomething(2.65);
^
..\Playground:19:24: note: candidates are:
..\Playground:5:6: note: void printSomething(int)
void printSomething(int x) {
^
..\Playground:9:6: note: void printSomething(float)
void printSomething(float x) {
^
but if I change
void printSomething(float x) {
cout << "I'm printing a float " << x << endl;
}
to
void printSomething(double x) {
cout << "I'm printing a float " << x << endl;
}
I will get output as
I'm printing a float 2.65
why is it?
but if it's only the integer it works fine
#include<iostream>
using namespace std;
void printSomething(int x) {
cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x) {
cout << "I'm printing a float " << x << endl;
}
int main() {
printSomething(3);
return 0;
}
Result
I'm printing an integer 3
Why isn't this working with float
Thankyou
2.65 is not a float literal, it's a double literal.
So the compiler doesn't know whether you want to convert the double to a float or an int and so issues the error.
In your first case, when writing float b = 2.65; the compiler assumes you know what you're doing, and calling the overload with b is unambiguous.
If you had written printSomething(2.65f); then that would also have been unambiguous: 2.65f is a float literal.
2.65 is considered a double. But you didn't provide an overload void printSomething(double x). Therefore the compiler must cast the value and it doesn't know if it should cast to float or int (both with precision loss`).
If you write 2.65f it is considered a float and it should work.
The reason for that is the conversion rules and overload resolution strategy. If C++ is unable to find an exact match on parameters, it looks for a conversion. The best conversion is an implicit one, that is widening (casting a data type to one that can hold all the values of the original type and potentially more), then a narrowing conversion (casting to a smaller data type, which may cause errors or loss of precision for some values), then a user-defined conversion.
As literal 2.65 is of type double, the compiler looks for conversions. There are two: double -> float and double -> int. They are both narrowing, which means they are equally good. The compiler is unable to pick the best one, thus reports an error.
To remedy this, you can either:
define overload for double as you did
use a float literal (2.65f) instead of a double

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)

What is the meaning of "*&" in C++ [duplicate]

This question already has answers here:
Function argument type followed by *&
(3 answers)
Closed 9 years ago.
I was looking at manual of ACE framework and came across this declaration
int ACE_Stream<>::get (ACE_Message_Block *& mb, ACE_Time_Value * timeout = 0)
I'm not able to understand what *& stands for. I know * is for pointer and & is reference. Can any one explain what is the meaning of this declaration.
Thanks in advance
So as #NPE said *& makes changes to pointer propagate back. But to understand I just wrote down some code sharing it so that it can help others understand this correctly
#include <iostream>
using namespace std;
class DoSomething
{
public:
int n;
DoSomething(int i){
n = i;
}
virtual ~DoSomething();
};
DoSomething::~DoSomething()
{
}
int dosomething(DoSomething * a)
{
cout << "Got value from caller: (in dosomething) = " << a << endl;
a = new DoSomething(25);
return 0;
}
int dosomethingElse(DoSomething *& a)
{
cout << "Got value from caller: (in dosomethingElse) = " << a << endl;
a = new DoSomething(15);
return 0;
}
int main(int argc, char *argv[])
{
DoSomething *d = new DoSomething(10);
cout << "Pointer to DoSomething: " << d << endl;
dosomething(d);
cout << "After dosomething value of d: " << d << endl << endl;
dosomethingElse(d);
cout << "After dosomethingElse value of d: " << d << endl << endl;
delete d;
return 0;
}
So as #NPE said here is out put of this
Pointer to DoSomething: 0x955f008
Got value from caller: (in dosomething) = 0x955f008
After dosomething value of d: 0x955f008
Got value from caller: (in dosomethingElse) = 0x955f008
After dosomethingElse value of d: 0x955f028
So indeed if I create a new instance inside function it will propagate only if I use *& and not just *
Thank you to every one for the answers.
I know * is for pointer and & is reference.
Correct. So what you have here is a pointer, passed by reference.
mb is a pointer that's being passed by reference. This means that if get() were to change the value of the pointer, the change would propagate back to the caller.