[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Why string can be added with 0?
From: |
Neil R. Ormos |
Subject: |
Re: Why string can be added with 0? |
Date: |
Sun, 18 Jul 2021 23:28:55 -0500 (CDT) |
Peng Yu wrote:
> I see this. I don't find anything about it in
> 6.2.1 Arithmetic Operators.
> $ gawk '{ print typeof($1), $1 + 0 }' <<< a
> string 0
> But it seems that there should be an error to
> add a string to 0?
It is not an error.
| 6.1.4.1 How awk Converts Between Strings and Numbers
| Strings are converted to numbers and numbers are
| converted to strings, if the context of the awk
| program demands it. For example, if the value of
| either foo or bar in the expression 'foo + bar'
| happens to be a string, it is converted to a
| number before the addition is performed. [...]
| [...] To force a string to be converted to a
| number, add zero to that string. A string is
| converted to a number by interpreting any
| numeric prefix of the string as numerals: [...]
| Strings that can't be interpreted as valid
| numbers convert to zero.
> Is it better to show some error instead of
> assuming a string as 0 in the context of
> arithmetic operations?
No. Awk's behavior, when an arithmetic operation
involving a string is attempted, of interpreting
as numeric however much of the string appears to
be numeric, without noisy error messages, is a
feature that makes it easier to write concise
programs that handle mixed string and numeric
input.
Besides, it has worked that way for eons, and
programmers rely on it. Changing it now would
break zillions of working programs.
If you prefer a programming language that does
intrusive type checking or routinely changes out
from under you so existing programs are rendered
useless, there are plenty of choices.