bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] Postdecrementing $NF


From: Aharon Robbins
Subject: Re: [bug-gawk] Postdecrementing $NF
Date: Sun, 08 Sep 2013 20:02:52 +0200
User-agent: Heirloom mailx 12.5 6/20/10

Hi. You can ignore the mail I just sent.

> Date: Sun, 08 Sep 2013 02:56:52 +0200
> From: Adam Zieli??ski <address@hidden>
> To: address@hidden
> Subject: [bug-gawk] Postdecrementing $NF
>
> $NF-- (or even $(NF--) ) - doesn't seem to work as intended.
>
> Instead of giving me a field value and decrementing FN after that, it 
> converts field value to number and then decrements it.
>
> Doing the same via variable set to NF works perfectly.

I think I see what's going on.  I believe that you've hit on
undefined behavior.  In a test case like:

        echo a b c | gawk '{ print $(NF--) }'

You are assuming that gawk does (or "should do") things in this order:

        1. Get the value of NF, save it
        2. Use the saved value to fetch the field at $NF
        3. Decrement NF at some point
        4. Print the field value

Gawk is actually doing the following:

        1'. Get the value of NF, save it
        2'. Decrement NF
        3'. Use the saved value to fetch the field at $NF
        4'. Print the field fetched using the saved value

The reason this does not work as you expect is that decrementing NF
reduces the number of available fields.  Thus when gawk executes step
3', there is no data there, because gawk has already thrown away the
original value that was there.

I don't believe that one behavior is more "correct" than the other;
of four different awks that I tested, including gawk, two do it the
one way, and two do it the other.

Thanks,

Arnold




reply via email to

[Prev in Thread] Current Thread [Next in Thread]