No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Structures de condition

L'instruction if()

Syntaxe de l'instruction if()

Remarque

Le groupe d'instructions qui dépendent de la condition est entouré d'accolades.
Dans nos exemples, une seule instruction dépend de la condition, et nous pouvons donc nous passer de mettre les accolades.

Sans accolades, seule l'instruction qui se situe immédiatement après la condition est soumise à cette dernière. Nous pouvons quand-mê prendre la bonne habitude de placer entre accolades l'instruction qui dépend de la condition, ce qui nous évitera tout risque d'erreur si nous décidons par la suite d'ajouter d'autres instructions dans ce bloc.

Contents Haut

La structure if() else

Syntaxe de la structure if() else

Exemple de structure if() else

  1. #include <stdio.h>
  2. void main (void)
  3. {
  4. int i;
  5. printf ("\nTry enter value 1: ");
  6. scanf ("%d", &i);
  7. if (i==1)
  8. {
  9. printf ("\nGood!");
  10. }
  11. else
  12. {
  13. printf ("\nBad!");
  14. }
  15. }

Contents Haut

Opérateur ternaire

L'opérateur ternaire nous permet une notation plus courte de l'instruction if.

Si l'expression entre parenthèses renvoie la valeur vrai (True, 1, etc.), l'instruction1 est exécutée. Sinon, c'est l'instruction2 qui est exécutée.

Attention, nous sommes limités à une seule instruction de part et d'autre du double point.

Ce type d'écriture correspond à :

Exemples avec l'opérateur ternaire

  1. function setColor($i){
  2. ( $i > 0 ) ? $this->color="#f00" : $this->color="#0f0";
  3. }

Il existe aussi une autre manière d'utiliser l'opérateur ternaire :

  1. function setColor($i){
  2. $this->color = ( $i > 0 ) ? "#f00" : "#0f0";
  3. }
  1. public void setColor(int i) {
  2. this.color=( i > 0 ) ? "#f00" : "#0f0";
  3. }

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 19/03/2002, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/programmation-if.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.