0
#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

manlio
  • 18,345
  • 14
  • 76
  • 126
Arun Dambal
  • 1
  • 1
  • 2

5 Answers5

4

int i has not been explicitly initialised. If i == 0 then nil (default boost::optional) is returned, when you print you will get 0.

T33C
  • 4,341
  • 2
  • 20
  • 42
3

You haven't initialized i. The behavior of this program is undefined. Set it to a non-zero value explicitly.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

In main() you haven't initialized i. And in test_func() you will never reach return (i);.

yasouser
  • 5,113
  • 2
  • 27
  • 41
  • if(i) retun boost::optional(1234); But why atleast this is not returning the value. What i want to do is i want to simulate the functionality of Boost::Optional – Arun Dambal Jan 25 '11 at 13:00
  • if(i) retun boost::optional(1234); But why atleast this is not returning the value. What i want to do is i want to simulate the operation of Boost::Optional pls help – Arun Dambal Jan 25 '11 at 13:02
1

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

Francesco
  • 3,200
  • 1
  • 34
  • 46
  • std::cout << test_func(1234) << endl; with this now its printing only 1, can u please modify my code snippet posted above.. it would be great help, thanks a ton. – Arun Dambal Jan 25 '11 at 12:57
0

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);
rve
  • 5,897
  • 3
  • 40
  • 64