help-gawk
[Top][All Lists]

## Re: Why string can be added with 0?

 From: Bob Proulx Subject: Re: Why string can be added with 0? Date: Sun, 18 Jul 2021 22:35:06 -0600

```Peng Yu wrote:
> I see this. I don't find anything about it in 6.2.1 Arithmetic Operators.

You were very close to the best section of the manual.  In the section
before that one is where the gawk manual talks about strings and
numbers.  In my manual it is section 6.1.4.1 "How 'awk' Converts
Between Strings and Numbers". The answer you seek is there.

https://www.gnu.org/software/gawk/manual/html_node/Strings-And-Numbers.html

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.  If numeric values appear in string concatenation, they are
converted to strings.  Consider the following:

two = 2; three = 3
print (two three) + 4

This prints the (numeric) value 27.  The numeric values of the variables
'two' and 'three' are converted to strings and concatenated together.
The resulting string is converted back to the number 23, to which 4 is

If, for some reason, you need to force a number to be converted to a
string, concatenate that number with the empty string, '""'.  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: '"2.5"' converts to 2.5, '"1e3"' converts to 1,000,
and '"25fix"' has a numeric value of 25.  Strings that can't be
interpreted as valid numbers convert to zero.

I abbreviated the information here.  See the manual for the full
section with more detail than I included here.

> \$ gawk '{ print typeof(\$1), \$1 + 0 }' <<< a
> string 0

That's correct.  It's a string but then adding 0 to the string forces
it to be a number.

> But it seems that there should be an error to add a string to 0? Is it
> better to show some error instead of assuming a string as 0 in the
> context of arithmetic operations? Thanks.

AWK was one of the first of the little languages to try to dynamically
do the right thing to simplify the programmer's task of writing a
program.  But following in the tradition of AWS is also Perl, Python,
Ruby, and many other dynamic languages that all behave the same way.
It's a design paradigm used to enhance programmer productivity.  If it
is used like a string then it is converted to a string.  If it is used
like a number then it is converted to a number.

Bob

```