View unanswered posts | View active topics It is currently Fri Feb 21, 2020 6:42 am






Reply to topic  [ 2 posts ] 
logic within if conditions is not working correctly 
Author Message
Rookie

Joined: Mon Mar 02, 2009 7:03 pm
Posts: 6
Post logic within if conditions is not working correctly
One of my costudents at university found another bug:
Code:
bool a = true;
if (a == true) {
 foo();
}
else {
 bar();
}

Behaviour: bar();
Expected behaviour: foo()

Code:
bool a = false;
if (a == false) {
 foo();
}
else {
 bar();
}

Behaviour: bar();
Expected behaviour: foo()

Code:
bool a = false;
if (a == true) {
 foo();
}
else {
 bar();
}

Behaviour: foo();
Expected behaviour: bar()

Code:
bool a = true;
if (a == false) {
 foo();
}
else {
 bar();
}

Behaviour: foo();
Expected behaviour: bar()

Here is a solution that "fixes" it partly:
Code:
bool valid (bool stmta, bool stmtb) {
 if (stmta) {
  if (stmtb) {
   return false;
  }
  else {
   return true;
  }
 }
 else {
  if (stmtb) {
   return true;
  }
  else {
   return false;
  }
 }
}


Now you can do this:
Code:
bool a = true;
if(valid(a,true)) {
 foo();
}
else {
 bar();
}

Now this code will result in the correct statement executed.


Fri Mar 06, 2009 3:58 pm
Profile
Guru
User avatar

Joined: Sat Mar 01, 2008 12:52 pm
Posts: 1030
Post Re: logic within if conditions is not working correctly
besides this bug (that has been reported before) there is in ANSI C actually no data type "bool" (like in Pascal).
true and false are values of a data Type char!
In RobotC this is likely.

In ANSI C "false" is equal to zero, and "true" is "not false" (unequal to zero).

But on the other hand the condition
Code:
 if (a==true)

is only "true" if a is =1,
but
Code:
if (a)

is also true if a is =2 or 4 or -90.

so: in conditions it is better to write
Code:
if (a)
//or
if (a!=false)

instead of
Code:
if (a==true)

_________________
regards,
HaWe aka Ford
#define S sqrt(t+2*i*i)<2
#define F(a,b) for(a=0;a<b;++a)
float x,y,r,i,s,j,t,n;task main(){F(y,64){F(x,99){r=i=t=0;s=x/33-2;j=y/32-1;F(n,50&S){t=r*r-i*i;i=2*r*i+j;r=t+s;}if(S){PutPixel(x,y);}}}while(1)}


Fri Mar 06, 2009 5:22 pm
Profile
Display posts from previous:  Sort by  
Reply to topic   [ 2 posts ] 

Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  



Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software for PTF.