How to use switch in C?

Asked

Viewed 801 times

2

I have to understand this code that my advisor gave me.

The opt after switch is mandatory?

The command break too? Why doesn’t it appear after the options case '?' and default?

if( argc <= 1) {
    fprintf(stderr, "\nparametros:\n-e arquivo de entrada\n-s arquivo de saida\n");
    exit(EXIT_FAILURE);
}
while ((opt = getopt(argc, argv, "e:s:")) != -1) {
    switch (opt) {

        case 's':
            saida=optarg;
            printf("Nome do arquivo de saida: %s\n", saida);
            errS++;
            break;

        case 'e':
            entrada=optarg;
            printf("Nome do arquivo de entrada: %s\n", entrada);
            errE++;
            break;


        case '?':
            fprintf(stderr, "\nFALTA PARAMETROS\n");

        default:
            fprintf(stderr, "%s \nparametros:\n-e arquivo de entrada\n-s arquivo de saida\n", argv[0]);
            exit(EXIT_FAILURE);
    }

4 answers

4


"Opt" after "switch" is required?

Well, no. There is an expression that gives some value that can be compared with the options of case. It’s usually a variable, but it doesn’t have to be, much less it has to be opt. Can, but it doesn’t make sense to have a literal, if you already know the value has no reason to compare.

The switch always take this value and find out which cases that fits into it, only one can be executed directly. But others can perform in sequence indirectly, then the case that he enter because of his literal (and in case always must have a literal) is equal to the value of switch will be the first, then he continues to enter into all the cases following.

This helps because often you want to do a kind of or, that is, more than one value is accepted, anyone he enters must execute all of the following execution blocks. It is common that in these cases only the last case that must do something have a code, the rest are empty, so:

switch (variavel) {
case 1:
case 2:
case 3:
    printf("entrou");
}

The "break" command also?

But to do this is not very useful, you will want him to stop executing at some point, you can not have to do all because there the switch no longer useful, you are not selecting anything.

That’s where the break, you use it to say that this block should be closed. Note that at the time you find the break the switch all is closed. So it gets better:

switch (variavel) {
case 1:
case 3:
    printf("impar");
    break;
case 2:
case 4:
    printf("entrou");
}

I put in the Github for future reference.

Why it does not appear after the options "case '?' and "default"?

You saw I didn’t use the break in the end. Why would I use it? In the end it ends even. No need. But many people put so anyway to organize, make more readable, identify the intention and facilitate a change that adds some block without risking forgetting to put the break which now becomes necessary.

The same goes for the default, there’s no point in having something shut down.

You may wonder why the last case did not need the break where there is the default next. The default it is special, only enter it if it does not enter the previous blocks, it is an OR of execution, there is no way to enter it if it entered in some case. It’s another name, the compiler knows it closed before.

In the default no one puts break makes no sense from any sane point of view.

  • Thank you! Just two questions: 1) "Can, but it doesn’t make sense to have a literal" what does literal mean in this context? 2) "The switch always brings this value and finds out which case fits it, only one can be executed directly" I didn’t understand your phrase, what is this 'ga'?

  • Literal is the same value, a number, a text, not a variable, constant, expression. I tidied up the text

2

"Opt" after "switch" is required?

Yes, it is mandatory, first because without it the command does not work, second because the variable "opt" contains the value that will eventually correspond to the value contained in any of the cases. If the values match, the code block is executed.

The "break" command too? Why does it not appear after the "case" and "default" options"?

The break command is not required, but it is used to break the execution flow. The default is enabled only if there is no match, and the case "?" is enabled only when the data entry is invalid. In both cases there is no need to interrupt the execution of the program.

  • Thank you. So basically you have the "e" and "s" options, if I type "d" the "?" option will be adopted?

  • The command receives the value (in this case string) that I type? That is, I have to type "and" or "s"?

  • In this case, there are still some command lines above which I omitted: if( argc <= 1) { fprintf(stderr, "nparameters: n-e input file n-s output file n"); Exit(EXIT_FAILURE); } while (opt = getopt(argc, argv, "e:s:")) != -1) {

  • I think the "?" option is executed when the input is empty. You have to look at the getopt function to see what it returns.

  • Yes, the command only executed when there is a match between the value of the switch and the case

  • Got it! EUREKA! Hahaha. The "opt" variable has to have value before it enters the "switch". I managed to run. I thought the messages (cases) would appear and then I would type the letter that was convenient. I managed to understand this "switch" command, thank you very much for the help!!!

Show 1 more comment

2

switch(opt) informs that the variable opt will be used to compare with the values after each case.

Each break signals that the control should go outside the block switch. So even though it’s not mandatory, it would be nice if you had a break at the end of the case '?'.

default is used for expressions not covered by cases previously declared. As this is the last case, you do not need the break to get out of the block switch.

1

The Operator opt is a variable, yes it is necessary is like a if() by placing it there it will take the value of this variable and compare with the CASE If you don’t find anything you’ll fall into DEFAULT

the Break is and is not necessary, it serves to bar the example process:

switch(num)
{

case 1:
x = i;
printf("Olha eu aqui");

case 2:
x = 20;
printf("Olha eu aqui");
break;
}

In this case the first case 1 will continue to case 2 and will drop two printf because there is no Break in case 1

  • Your example helped! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.