Tech Tip: Always declare variables for compiled mode
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: August 15, 2022
When developing for compiled applications, remember to declare typing for all variables. Even seemingly insignificant variables, such as ones that store a simple math result, should have their types declared appropriately to avoid unexpected results in compiled mode. For example, consider the following code:
$num:=Round(57/25.4; 3) ALERT("Result: "+String($num)) |
In interpreted mode, the alerted result would be the expected number: 2.244.
In compiled mode, however, the result would be a different number: 2.
This is because $num was not declared as Real, so the compiler assumes its type is the default typing for Numeric in database settings: Long integer.
After declaring the variable with the appropriate typing, the result in compiled mode will be correct.
var $num : Real $num:=Round(57/25.4; 3) ALERT("Result: "+String($num)) // Result: 2.244 in compiled mode |
To protect against these types of scenarios, it is recommended to set the Compilation Path setting to “All variables are typed”, so that the compiler will pick up any undeclared variables when compiling.