java - Labeled and Unlabeled break, continue in C# or C++ -
i have experience in c# works on java project take tour in java features. haired labeled , unlabeled break (it available in javascript) it's feature , shorten lot of time use labeled break in cases.
my question is, best alternative of labeled break in c# or c++, think can use goto keyword go out scope, don't prefer it. tried write code in java search in number in 2 dimensional array using labeled break it's easy:
public static void searchintwodimarray() { // here hard coded arr , searchfor variables instead of passing them parameter easy understanding only. int[][] arr = { {1,2,3,4}, {5,6,7,8}, {12,50,7,8} }; int searchfor = 50; int[] index = {-1,-1}; out: for(int = 0; < arr.length; i++) { (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == searchfor) { index[0] = i; index[1] = j; break out; } } } if (index[0] == -1) system.err.println("not found!"); else system.out.println("found " + searchfor + " @ raw " + index[0] + " column " + index[1] ); }
when try in c#:
- it's possible before use goto
i used flag instead of label:
public static void searchintwodimarray() { int[,] arr = { {1,2,3,4}, {5,6,7,8}, {12,50,7,8} }; int searchfor = 50; int[] index = { -1, -1 }; bool foundit = false; (int = 0; < arr.getlength(0); i++) { (int j = 0; j < arr.getlength(1); j++) { if (arr[i, j] == searchfor) { index[0] = i; index[1] = j; foundit = true; break; } } if(foundit) break; } if (index[0] == -1) console.writeline("not found"); else console.writeline("found " + searchfor + " @ raw " + index[0] + " column " + index[1]); }
so efficient way or there known alternative in c# , c++ of labeled break or labeled continue?
other goto, may better restructure c# logic like
public static string searchintwodimarray() { int[,] arr = { {1,2,3,4}, {5,6,7,8}, {12,50,7,8} }; int searchfor = 50; int[] index = { -1, -1 }; (int = 0; < arr.getlength(0); i++) { (int j = 0; j < arr.getlength(1); j++) { if (arr[i, j] == searchfor) { index[0] = i; index[1] = j; return("found " + searchfor + " @ raw " + index[0] + " column " + index[1]); } } } return("not found"); // console.readline(); // put line outside of function call }
Comments
Post a Comment