Saltar al contenido principal
LibreTexts Español

7.2: Anidamiento

  • Page ID
    82008
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Si una condición múltiple no lo corta, puedes anidar pruebas si/else. Anidar condicionales es fácil:

    if( test condition(s).. )
    {
        if( other tests.. )
        {
        }
        else
        {
        }
    }
    else
    {
        if( still other tests.. )
        {
        }
        else 
        {
        }
    }
    

    Puedes ir a muchos niveles de profundidad si lo deseas. Tenga en cuenta que C, a diferencia de Python, no requiere la sangría que se muestra, pero se espera formatear. Para la selección de un solo valor de una lista, puede usar la construcción switch/case. La plantilla se ve así:

    switch( test_variable )
    {
        case value_1:
            //...do stuff...
            break;
        case value_2:
            //...do other stuff...
            break;
        default:
            //...do stuff for a value not in the list...
            break;
    }
    

    La sección por defecto es opcional. Además, no tiene que ser el ítem final en la lista. Si se deja fuera un descanso, el código simplemente pasará al siguiente caso, de lo contrario, la ejecución del código salta a la llave de cierre. Además, las cajas se pueden apilar juntas. Las declaraciones de acción para cada caso pueden incluir cualquier declaración legal incluyendo asignaciones, llamadas a funciones, sif/else, otro cambio/caso, y así sucesivamente. Tenga en cuenta que no puede verificar rangos, ni los casos pueden ser expresiones. Los casos deben ser valores discretos. El siguiente ejemplo muestra todos estos. Las declaraciones de acción se sustituyen por simples comentarios.

    switch( x )
    {
        case 1:
            /* This code performed only if x is 1, then jump to closing
            brace */
            break;
        case 2:
            /* This code performed only if x is 2, then jump to closing
            brace */
            break;
        case 3:
            /* This code performed only if x is 3, but continue to next
            case (no break statement) */
        case 4:
        case 5:
            /* This code performed only if x is 3, 4, or 5,  */
            break;
        default:
            /* this code performed only if x is not any of 1,2,3,4, or
                5, then jump to closing brace (redundant here) */
            break;
    }
    

    A veces es muy útil reemplazar las constantes numéricas con valores #define. Por ejemplo, podrías estar eligiendo de un menú de diferentes circuitos. Crearías algunos valores #define para cada uno al inicio del archivo (o en un archivo de encabezado) como así:

    #define VOLTAGE_DIVIDER        1
    #define EMITTER_FEEDBACK       2
    #define COLLECTOR_FEEDBACK     3
    /* etc... */
    

    Entonces escribirías un interruptor/caso mucho más legible así:

    switch( bias_choice )
    {
        case VOLTAGE_DIVIDER:
            /* do volt div stuff */
            break;
        case EMITTER_FEEDBACK:
            /* do emit fdbk stuff */
            break;
        /* and so on... */
    }
    

    This page titled 7.2: Anidamiento is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by James M. Fiore via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.