逻辑判断原则

判定多个条件时,遵循从左到右,短路原则。

Q:

  if ( conditionA && conditionB ) 和 if ( conditionA || conditionB ),是先判断conditionA还是conditionB ?跟编译器有没有关系?

A:

  先判断conditionA再判断conditionB和编译器无关
  不过对于&&只要conditionA为假conditionB就不判断了
  对于||只要conditionA为真conditionB就不判断了
  因为结果已经知道了

在调程序的时候发现如下代码会报错:

    int largestRectangleArea(vector<int>& heights) {
        heights.push_back(0);
        stack<int>staIndex;
        int area = 0;
        for(int i = 0; i < heights.size(); i ++){
       //while(!staIndex.empty() && heights[i] <= heights[staIndex.top()]) Correct!
while( heights[i] <= heights[staIndex.top()] && !staIndex.empty() ){//Wrong!int h = heights[staIndex.top()]; staIndex.pop(); int leftId = staIndex.size() == 0? -1: staIndex.top(); int width = i - leftId - 1; area = max(area, h * width); } staIndex.push(i); } return area; }

 

posted on 2016-10-10 10:30  暴力的轮胎  阅读(197)  评论(0编辑  收藏  举报

导航