Monday, April 9, 2018

How do you work with an anonymous function in C++?

Let us take the example of multiplication of two integers, the resulting value is
also an integer. Now we can return the value after multiplication into a multiply function using an anonymous object that holds the value after multiplication.

In Visual Studio 1027 Community you would start a Windows Console Application as described in a previous post.

This is a C++ Windows Console Application created using VS 21107 Community. The name of the function is AnonFn and the AnonFn.cpp file is reproduced here:

--------------
// AnonFn.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
#include

int multiply(int x, int y)
{
 return (x * y); // This return value is held in an anonymous object
}
int main()
{
   cout << multiply(8, 7);
 return 0;
}

After Building this use Ctrl+F5 to run the program and you should see the console. Make sure if you make changes to the program that you build again and this message may show up, if you have not built the program.



Now after building the project click Ctrl+F5 to execute the program. This is what you will see in the DOS screen that gets displayed.


What if you try to multiple 8 and 7.8? the result will still be 56.

No comments: