Difference between revisions of "C programming/Caveats"

From Teknologisk videncenter
Jump to: navigation, search
m (added Category:C++ using HotCat)
m (Logical && and logical ||)
 
(One intermediate revision by the same user not shown)
Line 10: Line 10:
 
</source>
 
</source>
 
The statement of the left side of && evaluates to ''false'' the rigth side of the statement is never evaluated - and j is never incremented.
 
The statement of the left side of && evaluates to ''false'' the rigth side of the statement is never evaluated - and j is never incremented.
 +
 +
<br/>or<br/>
 +
 +
<source lang=c>
 +
    i=0;
 +
    j=8;
 +
if (( i == 0 ) || (( j++ ) > 0 )) {
 +
  ...code...
 +
}
 +
</source>
 +
The statement of the left side of || evaluates to ''true'' the rigth side of the statement is never evaluated - and j is never incremented.
 +
 
=Links=
 
=Links=
 
*[http://www.eetimes.com/electronics-blogs/other/4394720/Sequence-points-?Ecosystem=embedded&cid=Newsletter+-+Whats+New+on+Embedded.com C Sequence points]
 
*[http://www.eetimes.com/electronics-blogs/other/4394720/Sequence-points-?Ecosystem=embedded&cid=Newsletter+-+Whats+New+on+Embedded.com C Sequence points]

Latest revision as of 16:17, 10 February 2013

This article contains C programming syntaxes and equations that behave in a strange way.

Logical && and logical ||

When using the logical AND (&&) or the logical OR (||) the expression is evaluated from left to right. Consider the following code.

    i=1;
    j=8;
 if (( i == 0 ) && (( j++ ) > 0 )) {
  ...code...
 }

The statement of the left side of && evaluates to false the rigth side of the statement is never evaluated - and j is never incremented.


or

    i=0;
    j=8;
 if (( i == 0 ) || (( j++ ) > 0 )) {
  ...code...
 }

The statement of the left side of || evaluates to true the rigth side of the statement is never evaluated - and j is never incremented.

Links