Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(ex2.cpp): repleced if and else if with an array #292

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

FilippoMarletta
Copy link

repleced if and else if with an array to reduce the number of comparisons

repleces `if` and `else if` with an array to reduce the number of comparisons
Copy link

@makapx makapx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

L'else potrebbe non servire. Ti basta fare un return dentro l'if. Se non è in quel range è sicuramente non valido

Copy link
Collaborator

@TendTo TendTo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

La soluzione è corretta, anche se metterei un endl ad accompagnare il cout dopo il giorno della settimana.
Inoltre spesso viene consigliato di rendere il codice più leggibile usando la macro #define EXIT_SUCCESS 0, già presente in stdio.h, da sostituire al return 0; finale.
Ma perché non fare un po' di inutile show-off e rimuovere del tutto gli if?

// main
  unsigned int week; // Lavoriamo con interi unsigned

  cout << "Enter week number(1-7): " << endl;
  cin >> week;

  string WeekDays[8] = {"Monday", "Tuesday",  "Wednesday", "Thursday",
                        "Friday", "Saturday", "Sunday",    "Invalid input! Please enter week number between 1-7."};

  // Assumendo che [1 = Lunedì, 2 = Martedì, ..., 7 = Domenica]
  unsigned int choice = min(week - 1, 7u); // La u accanto al 7 indica un intero unsigned

  // Se la scelta è in [1, 7], si avrà il giorno della settimana richiesto  
  // Altrimenti il risultato sarà il messaggio di errore. È chiaro il peché?
  cout << WeekDays[choice] << endl; 

@FilippoMarletta
Copy link
Author

Grazie dei consigli, apporterò subito queste migliorie.
Visto che posso rimuovere l'else a questo punto applico la soluzione molto elegante di @TendTo e rimuovo del tutto gli if.

…and other improvements

replaced `if`/`else` with min(week-1,7), `int` with `unsigned int` and `return 0` with `return
EXIT_SUCCESS`; improved the readability of WeekDays array;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants