簡體   English   中英

如何擺脫這些警告?

[英]How to get rid of these warning?

bool Order::add(std::istream& is){
   int copies;
   bool keepgoing = true;

   while (keepgoing){   
      std::cout << "Quantity (0 to quit) : ";
      is >> copies;  
      if (copies==0){
         keepgoing = false;
         return false;

      }else if (copies<0){
         std::cout << "Enter a positive number. Try again."<<std::endl;
      }else{
         no_copies+=copies;
         return true;
      }
   }
}

它顯示警告,控件可能會達到非無效功能的終點。 不明白。

整個keepgoing業務都是多余的-您僅在退出該功能之前就將其設置為false 將其替換為“ forever”循環,警告應消失:

bool Order::add(std::istream& is){
   int copies;

   for(;;) {
      std::cout << "Quantity (0 to quit) : ";
      is >> copies;  
      if (copies==0){
         return false;
      }else if (copies<0){
         std::cout << "Enter a positive number. Try again."<<std::endl;
      }else{
         no_copies+=copies;
         return true;
      }
   }
}

請注意,您並不是一直在檢查輸入是否成功。

基本上,您的代碼太復雜,編譯器無法給出更有用的警告。

您添加了一個keepgoing變量,該變量不會添加任何內容。 在您有意義地使用其值的所有情況下,其值都將為true 但是,編譯器無法確定在所有相關情況下它始終為true ,並考慮了將它意外設置為false的可能性。 誰知道,也許您的編譯器支持您使用調試器修改變量。

如前所述,您可以輕松擺脫該變量:無論while循環的條件如何, return語句都將導致while循環退出。

return語句移到

     keepgoing = false;

到最后。

     return false;

喜歡:

bool Order::add(std::istream& is){
   int copies;
   bool keepgoing = true;

   while (keepgoing){   
      std::cout << "Quantity (0 to quit) : ";
      is >> copies;  
      if (copies==0){
         keepgoing = false;
         // No need to return from here.
         // Changing keepgoing to false will break the loop.
      }else if (copies<0){
         std::cout << "Enter a positive number. Try again."<<std::endl;
      }else{
         no_copies+=copies;
         return true;
      }
   }

   return false;
}

聽起來編譯器在警告方面不太清楚。 該警告試圖說明如果函數到達末尾,則不會返回任何值。 由於您的while循環可能會退出-您正在檢查bool變量,而不僅僅是說while (true) -編譯器告訴您並非代碼中的所有路徑都返回值,所以這很不好。

許多編譯器將while (true)視為警告,因為它們很容易導致無限循環。 對於無警告的代碼,移動行

return false

從您擁有它到功能的最后。 這樣,當用戶輸入0時, keepgoing變量將中斷while循環並下降到函數的末尾,並返回false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM