Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #39117

Re: Why i++ can not be used in conditional operator?

Newsgroups comp.lang.java.programmer
Date 2019-08-20 11:03 -0700
References <qj56aa$6jg$1@gioia.aioe.org> <qj5mus$8u9$1@news4.open-news-network.org>
Message-ID <e7d22b5d-e830-460f-9c9b-a3267bdbd1f8@googlegroups.com> (permalink)
Subject Re: Why i++ can not be used in conditional operator?
From taqmcg@gmail.com

Show all headers | View raw


On Friday, August 16, 2019 at 3:45:42 AM UTC-4, Marcel Mueller wrote:
> Am 16.08.19 um 05:01 schrieb Xue Feng:
> > But in Java the same expression will cause the compiler to 
> > issue errors. I wonder the 'i++' (or 'i--') is rather a statement than 
> > an expression, as such can not return a value. Is that true?
> 
> You are on the right way. It is the other way around.
> 
> i++ is an /expression/ and returns a value, namely i before the 
> increment since you used the postfix operators. The conditional operator 
> is also always an expression that returns one of the values. But now you 
> have a value followed by a semicolon, and that is not allowed.
> AFAIK only results of function calls or assignment operators can be 
> discarded.
> 
> However, the desired result could achieved in one line like that:
>    i += inc ? 1 : -1;
> 
> 
> Marcel

I don't think there is any problem here...   The following code works for me.

public class Test {
    public static void main(String[] args) {
	boolean b = false;
	int     i = 1;
	int     j;
	
	System.out.println("I starts out:"+i);
	j = b ? i++: i--;
	System.out.println("J is now:"+j);
	System.out.println("I is now:"+i);
    }
}
and finishes with j=1 and i=0.

While I would never do this (in fact I never use the ++ or -- operators, only the += and -= operators) Java seems happy enough with it.

Perhaps the OP's issue was with the much stricter typing of Java.  E.g., maybe his 'inc' was an integer type and not a boolean.

    Regards,
    Tom McGlynn


Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Why i++ can not be used in conditional operator? Xue Feng <xf.lotus@yahoo.com> - 2019-08-16 11:01 +0800
  Re: Why i++ can not be used in conditional operator? Marcel Mueller <news.5.maazl@spamgourmet.org> - 2019-08-16 09:45 +0200
    Re: Why i++ can not be used in conditional operator? taqmcg@gmail.com - 2019-08-20 11:03 -0700

csiph-web