tags:

views:

139

answers:

2

Hi,

I wanted to know why the following code crashes.

int main( ) 
{  
    int arr = 1 && arr;
    return 0; 
}

BUT not with the below code

int main( ) 
{  
    int arr = 0 && arr;
    return 0; 
}

Thanks in advance

+11  A: 

0 && arr
The above expression is false because of 0, so arr is not checked unlike 1 && arr where arr has to be checked to evaluate the value for expression.


You should try:

int main(){
  int a = 0 && printf("a"); //printf returns number of characters printed, 1
  int b = 1 && printf("b");
  return 0;
} 
N 1.1
Awesome Answer Thanks :)
mahesh
+4  A: 

Because of short circuit evaluation of boolean expressions. In the first example the left side of the && operator evaluates to true so the right is evaluated. In the second case the left is false so the right is never evaluated.

Steve Fallows