Sign in Join
Wiki copytemporary

Val: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Val

OldNewLine
1+The [[Procedure|procedure]] [`system.val`](https://www.freepascal.org/docs-html/rtl/system/val.html) attempts to convert a string representation of a numeric value into a numeric value variable. This [[Borland Pascal]] extension is part of the default [[RTL|run-time library]] delivered with the [[FPC|FreePascal compiler]], but otherwise not standardized.
2+
3+## usage
4+
5+The formal signature reads:
6+
7+``` pascal
8+procedure val(const s: string; var v; var code: word)
9+```
10+
11+`S` is a [[String|string]]-type expression; it must be a sequence of characters that form a (possibly signed) number or enumerated type value. `V` is an ordinal or [[Real|real]]-type variable. `Code` is a [[Word|word]] integer variable.
12+
13+If the string `s` can not be converted to a numeric value, `code` holds the index of the first character causing troubles; otherwise `code` is zero, indicating success.
14+
15+> **Note:** In contrast to `read`, the value of `v` remains unchanged if no data (i.e. empty string `s`) is available. No `default` value is assigned.
16+
17+The procedure `val` is so useful, since it does not trigger [[runtime error|run-time errors]] or [[Exceptions|exceptions]]. Unlike [[Read|read]] the user can be supplied with more useful error messages telling which character is not a numeric symbol. The power of `val` lies in its capability to also convert enumerated types *by their named values*.
18+
19+``` pascal
20+program valDemo(input, output, stdErr);
21+type
22+ decision = (no, yes, maybe);
23+var
24+ s: string;
25+ r: decision;
26+ c: word;
27+begin
28+ writeLn('Are you OK?');
29+ readLn(s);
30+ val(s, r, c);
31+ writeLn('So ', r, '.');
32+end.
33+```
34+
35+Note, as a general design principle this feature should not be used for user responses like this example shows, since it thwarts internationalization. Localization in general is not possible with `val`, most notably the decimal separator – in some regions a [[Comma|comma]], in others a [[period]] – can not be customized; it is always a period, as it is standard in your [[Standard Pascal|Pascal]] source code. However, `val` still may be useful for reading and parsing *generated* data.
36+
37+## see also
38+
39+- [[Str|system.str]] performs the reverse action
40+- [[RTTI]]
41+- [String operations](https://BorlandPascal.FanDom.com/wiki/String_operations) in *BorlandPascal Fandom Wiki*
42+
43+---
44+*From the Free Pascal wiki, page "Val", as it stood on 2023-02-07 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
45+Category: Code

Back to history