溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++中為什么循環(huán)中盡量少用break和continue

發(fā)布時(shí)間:2021-11-26 13:36:52 來(lái)源:億速云 閱讀:312 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“C++中為什么循環(huán)中盡量少用break和continue”,在日常操作中,相信很多人在C++中為什么循環(huán)中盡量少用break和continue問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C++中為什么循環(huán)中盡量少用break和continue”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

ES.77:循環(huán)中盡量少用break和continue

Reason(原因)

在不規(guī)整的循環(huán)體中,很容易忽略掉break和continue。循環(huán)中的break和switch語(yǔ)句中的break存在顯著的不同(同時(shí)你還可以將在循環(huán)體內(nèi)放入switch語(yǔ)句或者在switch語(yǔ)句中放入循環(huán)。)

Example(示例)

switch(x) {
case 1 :
   while (/* some condition */) {
       //...
   break;
   } //Oops! break switch or break while intended?
case 2 :
   //...
   break;
}
Alternative(可選項(xiàng))

Often, a loop that requires a break is a good candidate for a function (algorithm), in which case the break becomes a return.

需要break的循環(huán)通常很適合做成函數(shù)(算法),這是break可以變成return。

//Original code: break inside loop
void use1()
{
   std::vector<T> vec = {/* initialized with some values */};
   T value;
   for (const T item : vec) {
       if (/* some condition*/) {
           value = item;
           break;
       }
   }
   /* then do something with value */
}

//BETTER: create a function and return inside loop
T search(const std::vector<T> &vec)
{
   for (const T &item : vec) {
       if (/* some condition*/) return item;
   }
   return T(); //default value
}

void use2()
{
   std::vector<T> vec = {/* initialized with some values */};
   T value = search(vec);
   /* then do something with value */
}

Often, a loop that uses continue can equivalently and as clearly be expressed by an if-statement.

通常,使用continue的循環(huán)可以等價(jià)地,清晰地表示為if語(yǔ)句。

for (int item : vec) { //BAD
   if (item%2 == 0) continue;
   if (item == 5) continue;
   if (item > 10) continue;
   /* do something with item */
}

for (int item : vec) { //GOOD
   if (item%2 != 0 && item != 5 && item <= 10) {
       /* do something with item */
   }
}
Note(注意)

If you really need to break out a loop, a break is typically better than alternatives such as modifying the loop variable or a goto:

如果你確實(shí)需要終端一個(gè)循環(huán),break通常會(huì)優(yōu)于修改循環(huán)變量或goto語(yǔ)句。

到此,關(guān)于“C++中為什么循環(huán)中盡量少用break和continue”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI