01: // operatore logico AND, > e cortocircuito valutazioni espressioni logiche
02: 
03: #include<stdio.h>
04: #include<stdlib.h>
05: 
06: int main(int argc, char **argv){
07:   int n, d;
08: 
09:   printf("Please, enter two positive integer numbers: ");
10:   scanf("%d", &n);
11:   scanf("%d", &d);
12: 
13:   int risultato = (d != 0 && n%d == 0); 
14:   printf("Il risultato dell'espressione (%d != 0 && %d%%%d == 0) e' %d\n", d, n, d, risultato);
15: 
16:   // lets try the same expression simply inverting the operands
17:   // formally this should be the same as previous one 
18:   risultato = (n%d == 0 && d != 0);
19:   printf("Il risultato dell'espressione ( %d%%%d == 0 && %d != 0) e' %d\n", n, d, d, risultato);
20: 
21:   /* FIXME 
22:      when we input 0 for d the program fails during execution. Why?
23:      When d == 0, n%d can not be computed sine it implies a division by 0
24:      But in both conditions we have n%d, and therefore why the evaluation
25:      of the first expression does not fail?
26:      Anyway, when logical operators are used, shortcuts are applied.
27:      The evaluation of && stops when the first operand is false, since
28:      this implies that the whole expression is obviously false.
29:      Therefore the evaluation of (d != 0 && n%d == 0) stops when d == 0 
30:      without even bothering to compute n%d == 0
31:      This is not happening when the second expression is evaluated.
32:      In such a case, initially the system tries to evaluate n%d == 0
33:      therefore failing...
34: 
35:    */
36: 
37: 
38: 
39:   return 0;
40: }
41: 
42: 


Se avete commenti o osservaƶioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it