Typed literals
- Ivaylo Fiziev
- May 9
- 2 min read

What are literals? These are the constant values that we use in the code. Examples are: numbers ( 1, 2, 10#1, 16#FF, 8#77, 3.14, 2E-10 ), strings ( 'foo' ) etc.
What are typed literals then? These are the same values but this time they have a type assigned to them.
Examples: numbers ( BYTE#1, INT#2, UINT#10#1, UDINT#16#FF, WORD#8#77, REAL#3.14, LREAL#2E-10 ), strings ( STRING#'foo' ), time intervals ( TIME#10ms, T#2m, TIME#2h_3m_2s )
Q: Why do we need the type to be explicit?
A: Types help when evaluating expressions.
If the type is not specified the SCL interpreter makes some assumptions about the type of the literal. There are cases when these assumptions may lead to unexpected results. The typed literals allow you to make the interpreter skip this step and take the type you provide for granted.
Lets take this example: Imagine you have a LREAL output that is supposed to return the simulation time in seconds. SIM_TIME() returns milliseconds so we simply do:
#out := SIM_TIME() / 1000; // convert ms to sec
It seems natural to do it this way but you will be amused when you check the result. The values you get will be discrete instead of floating point. Why? This is due to the type of the expression we use. By definition the type of the expression depends on the type of the operands inside. SIM_TIME returns a value of type UDINT and 1000 is assumed to be a DINT.
In this case the expression type is UDINT. The value of the expression is evaluated as a UDINT and then this value is cast to LREAL. This inevitably leads to the discrete results that we observe.
Q: How should we fix this?
A: Just change the literal type:
#out := SIM_TIME() / LREAL#1000; // convert ms to sec
This time the type of the expression is LREAL and the result is a floating point number.
If you use the 1000.0 literal the expression type will be REAL. It might work in the majority of cases but could be a cause of precision loss at some point.
As of version 2509 we support only numeric and time typed literals.
Now you know!
Bye
Kommentare