Skip to content
Tcl Source Code View Ticket
Login

View Ticket

2001-03-20
23:43 • Closed ticket [410043ffff]: "if" does not evaluate same as "expr&... artifact: 2c97a15461 user: dkf
23:23 • Ticket [410043ffff]: 4 changes artifact: e239a82c84 user: nobody
16:17 • New ticket [410043ffff]. artifact: 1abf1ca0e8 user: nobody

"if" does not evaluate same as "expr"

Closed / Invalid410043ffffffffffffffffffffffffffffffffffCreated 26 years agoUpdated 26 years ago
Descriptionplain2001-03-20 16:17:01
The following script produces strange output.

Script:
#-----------------------------------------------
set vmin 1.3
set vmax 1.7
set idx  4
set incr 0.1

set newval [expr {$vmin+int($idx)*$incr}]

if { $newval > $vmax } {
    puts "Bare 'if' says $newval > $vmax"
} else {
    puts "Bare 'if' says $newval <= $vmax"
}

if { [expr $newval > $vmax] } {
    puts "'if' with expr says $newval > $vmax"
} else {
    puts "'if' with expr says $newval <= $vmax"
}
#-----------------------------------------------

Output:
Bare 'if' says 1.7 > 1.7
'if' with expr says 1.7 <= 1.7

As you see, the "if" command returns a different answer
depending on whether or not you use expr.
nobodyplain2001-03-20 23:23:36
Logged In: NO 

The problem seems to be that the arguments to [expr] aren't braced.  I added:

if { [expr {$newval > $vmax}] } {
    puts "'if' with braced expr says $newval > $vmax"
} else {
    puts "'if' with braced expr says $newval <= $vmax"
}

and it agreed with the raw [if].  I imagine this has to do with shimmering but that's a guess.  You ought to 
brace [expr] arguments for performance anyway so this doesn't seem like a real issue.

-- Chris Nelson ([email protected]), who can't manage to log into SorceForge reliably
dkfplain2001-03-20 23:43:47
Logged In: YES 
user_id=79902

This problem (a known feature of Tcl that is unlikely to
ever be altered for a host of deep reasons) stems from the
fact that 0.1 is not a precisely representable floating
point number and that arguments to [expr] are [concat]enated
before evaluation. Rerun the script with tcl_precision set
to 17, or with the expression to pass to [expr] in {braces},
and you'll get agreement between the "bare if" and the "if
with expr".

If this matters very much, use fixed-point arithmetic
instead.
Log in (anonymous is fine) to add a comment.