#include < stdio.h>
int main(){
int t;
int i=2;
int j=4;
t=(i+=2,j==i);
printf("%i\n",t);
return 0;
}
Running it produces 1 as output.
However, compiling
class Testit{
public static void main(String args[]){
boolean t =true;
int i=2;
int j=4;
t=(i+=2,j==i);
}
}
Produces
C:\JAVA> javac Testit.java
Testit.java:6: ')' expected.
t=(i+=2,j==i)
However, one can use comma's for sequential execution within the control expressions of a for statement.
In particular,
public class T1{
public static void main(String args[]){
int i,j;
for(i=1,j=2;(i+j)< 10;i++,j++)
System.out.println(new Integer(i+j).toString());
}
}
compiles and produces
C:\drop> java T1 Symantec Java! JustInTime Compiler Version 210.054 for JDK 1.1.2 Copyright (C) 1996-97 Symantec Corporation 3 5 7 9
Valid C code such as
int a;
a=expression;
if(a = 1) /* it is now! */
{ something}
produces a Java compile error.
First a class that distinguishes the actions associated with a labeled continue from those of an unlabeled break
class ContinTest{
public static void main(String args[]){
boolean t=true;
int i =1,j=0;
b:while(j< 5){
i=1;j++;
System.out.println("The times table for "+j);
while(true){
System.out.println(i*j);
if(i==5){
if(j < 5)
continue b;
else
break;
}//if
i++;
}//while
System.out.println("all done");
}//b
}//main
}//class
Here is the output. Note that the "all done" only executes on break
/siegel/home/public_html%java ContinTest The times table for 1 1 2 3 4 5 The times table for 2 2 4 6 8 10 The times table for 3 3 6 9 12 15 The times table for 4 4 8 12 16 20 The times table for 5 5 10 15 20 25 all done
Next a labeled break statement.
class BreakTest{
public static void main(String args[]){
boolean t=true;
a:{
b:{
c:{
System.out.println("before");
if(t)break b;
}//c
System.out.println("will not execute");
}//b
System.out.println("next to execute");
}//a
}//main
}//classHere is the output.
C:\JAVA> java BreakTest before next to execute
At first glance, it appears that labeled breaks and continues can be used to simulate a goto, however, there are restrictions on their use as illustrated by the following output which results from removing the if clause from the statement containing the break
BreakTest.java:11: Statement not reached.
System.out.println("will not execute");
^
1 error
Interestingly, if you insert the lineif(true) break b;
The program compiles and runs as before. More on this point later.