Click to See Complete Forum and Search --> : assert function?
PeiFeng
May 2nd, 2003, 02:15 AM
my question is about the assert() with
the following code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <conio.h>
#include <set>
#include <assert.h>
typedef set<int> intSet;
int main(int argc, char* argv[])
{
intSet::_Pairib pib;
for (int i=0;i<1000;i++)
//assert( s1.insert(ID("xie",i)).second );
{
pib=s1.insert(ID("xie",i));
assert(pib.second);
}
..................
getch();
return 0;
}
it works OK!
but why i cant used the assert statement?
i think it's equal to the statements in the brace!
dude_1967
May 2nd, 2003, 02:52 AM
Victory,
The compressed single line should give the same functionality as the expanded two lines. I would put the single line in braces for clarity.
Sincerely, Chris.
#include <iostream>
#include <string>
#include <algorithm>
#include <conio.h>
#include <set>
#include <cassert>
using namespace std;
typedef set<int> intSet;
intSet s1;
#define ID(a, b) 3
int main(int argc, char* argv[])
{
intSet::_Pairib pib;
for(int i = 0; i < 1000; i++)
{
assert( s1.insert(ID("xie",i)).second );
// pib = s1.insert(ID("xie",i));
// assert(pib.second);
}
return 1;
}
Graham
May 2nd, 2003, 03:43 AM
Except, of course, that when you compile for release mode, the expression in the assert statement will not get executed.
The two versions are not equivalent, and the single-statement version will lead to problems. Never put code with side-effects into an assert, only examine data.
dude_1967
May 2nd, 2003, 03:53 AM
Oh yeah,
I guess I had forgotten that assert code might not even get compiled under most conditions. This wouldn't work very well...
Thanks for that key reminder Graham.
Maybe it would be better to store second.pib in an intermediate variable and assert the variable.
Sincerely, Chris.
:)
Graham
May 2nd, 2003, 04:47 AM
Of course, up to this point, I've refrained from wondering why on earth this code is reliant on a detail of one particular STL implementation. _Pairib is not part of the standard interface to std::set (the leading underscore is a dead giveaway) and you have to wonder why any piece of code would need to bother with it.
PeiFeng
May 2nd, 2003, 08:39 PM
Graham,Thank you for your advice
Originally posted by Graham
Never put code with side-effects into an assert, only examine data.
--·çÖ®ÐÐ
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.