Reputation: 1
#include </usr/include/boost/optional.hpp>
#include <iostream>
using namespace std;
boost::optional<int> test_func(int i)
{
if(i)
return boost::optional<int>(1234);
else
return boost::optional<int>();
return (i);
}
int main()
{
int i;
test_func(1234);
std::cout<< test_func(i) << endl;
return 0;
}
Could any body please tell me y am i getting the value of i as 0, what i want to do is i want to print the values of " i " after entering into " if " condition & also in the " else" part.
Please do the needful, refer me any modification's Thanks Arun.D
Help is greatly appreciated.. thanks in advance
Upvotes: 0
Views: 3310
Reputation: 6055
Besides the unitialized i
and not reaching return i;
other already mentioned:
You are printing the bool conversion of boost::optional
. When the optional contains a value it prints 1
, when the optional does not contain a value it prints 0
.
I think you mean something like:
boost::optional<int> result(test_func(i));
if (result)
{
std::cout << *result;
}
else
{
std::cout << "*not set*";
}
and not
std::cout << test_func(i);
Upvotes: 0
Reputation: 3250
Other have already commented: you are using i without initializing and it is default initialized to 0. But maybe you are wondering why you don't see 1234: this is because you are discarding the return value (hard-coded to boost::optional(1234) ). Maybe you meant to write
std::cout << *test_func(1234) << endl; // by using operator* you are not discarding the return value any more
std::cout<< test_func(i) << endl;
Read the documentation and look at the examples for more information
Upvotes: 1
Reputation: 4429
int i
has not been explicitly initialised. If i == 0
then nil (default boost::optional) is returned, when you print you will get 0.
Upvotes: 4
Reputation: 5177
In main() you haven't initialized i
. And in test_func()
you will never reach return (i);
.
Upvotes: 2
Reputation: 363547
You haven't initialized i
. The behavior of this program is undefined. Set it to a non-zero value explicitly.
Upvotes: 3