+ 1
How can I interpret it?
#include <iostream> using namespace std; int f1(int x, int y) { return x + y; } int f2(int x, int y) { return x - y; } int main() { cout << f2(2, 2); int(*f2)(int, int)=f1;//this part is what i dont know cout << f2(2, 2); f2 = ::f2;//this part too cout << f2(2, 2); } //This code is from a challenge. Maybe function replacing..? when the output is known to me as 040
3 Réponses
+ 7
Here is the same code with details in comments:
#include <iostream>
using namespace std;
int f1(int x, int y) { return x + y; }
int f2(int x, int y) { return x - y; }
//By far, user has just created two functions...
int main() {
cout << f2(2, 2);
// Prints 0, as 2-2...
int(*f2)(int, int)=f1;
/*
Here. we declare a pointer to a function and assign it with the function f1. Thus now, f2 will also return x+y, as it is a alterante name now for f1... A pointer to a function has the following syntax :
return_type(* function_name)(parameter_types_as_list) = function_which we want a rename of...
Eg - int(*sub)(int,int)=f2;
cout<<sub(2,2);
//Will be replaced by f2(2,2);
Thus in this example, after this declaration, both f1 and f2 work in the same way and return the same output...
*/
cout << f2(2, 2);
//Is f1(2,2), So, Prints 4...
f2 = ::f2;
/*
Now we reassign the pointer f2 to the real function f2, and to make the assignment successful, we use the scope resolution or :: operator to assign the real f2 to the pointer, and not the pointer to the pointer itself ( Thus we dont do f2=f2)...
Thus, f2 again becomes f2 and returns x-y...
*/
cout << f2(2, 2);
// Prints 0, as it is the original...
}
+ 4
@nameoo non
Glad to know that I could be of some help...
You're welcome ^_^
+ 1
Thank you so much. I got better thanks to you.