1

the program will run correctly if with no cout; why? something wrong with output cache?

#include<algorithm>
#include<iostream>
#include<vector>

using namespace std;


class fn
{
    public:
        int i;
    bool operator()(int,int)
    {
        ++i;
        cout<<"what the poodles?\n";
    }
};
int main()
{
    vector<int> temp(9,9);
    vector<int> tmp(2,3);
    fn f;
    vector<int>::iterator ite;
    ite=find_first_of(temp.begin(),temp.end(),tmp.begin(),tmp.end(),f);
    if(ite==temp.end())cout<<"Pomeranians!\n";
    //cout<<"compared "<<f.i<<" time(s)\n";//if note this ,you'll get defferent output.
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
tqtifnypmb
  • 11
  • 3

1 Answers1

2

Three thoughts:

  1. fn::operator()(int, int) returns a bool but has no return statement. That function is not proper C++.

  2. When I fix that line, I get the output that I would expect. If the first part of the answer doesn't fix your problem, could you elaborate in your question with the output that you see, and the output that you expect, and a note about how they differ.

  3. You're also incrementing an uninitialized variable fn::i. This isn't going to do anything helpful for you. You should initialize it in a constructor. If you attempt to print this variable (or inspect it in any way), it could have any value, because it's starting value could have been anything (possibly 0, possibly anything else).


To elaborate, my compiler warned me of the following problem:

foo.cc:16:3: warning: control reaches end of non-void function [-Wreturn-type]

To fix this, I added a return false; at the end of the functor, and I see the following output, which makes sense to me.

[11:47am][wlynch@watermelon /tmp] ./foo
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
Pomeranians!
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • but why it also run right if I note the statement with cout,before I added a return false?(the output same as you posted).....ps variable i just to count,I used global variable in my code; – tqtifnypmb Mar 15 '13 at 05:47
  • The code you had written before you added the return false was not valid code. You must end a function with a return statement, or the entire program is invalid, and weird side-effects can occur. These side-effects may be what you expect, or not what you expect. Also, about your cout statement, please read my third point, and let me know if that doesn't make sense. – Bill Lynch Mar 15 '13 at 14:39