bug-gawk
[Top][All Lists]
Advanced

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

Re: [bug-gawk] Postdecrementing $NF


From: Davide Brini
Subject: Re: [bug-gawk] Postdecrementing $NF
Date: Sun, 8 Sep 2013 20:02:15 +0200

On Sun, 08 Sep 2013 20:02:52 +0200, Aharon Robbins <address@hidden>
wrote:

> 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.

But then why using a variable in the same way works as expected?

$ echo a b c | awk '{ a = NF; print $(a--) }'
c

-- 
D.



reply via email to

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