Is this necessary?

This is a discussion on Is this necessary? within the C++ Programming forums, part of the General Programming Boards category; A simple program I did for completing an exercise: Code: //This program reads the <char> from the keyboard, and then ...

  1. #1
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77

    Is this necessary?

    A simple program I did for completing an exercise:

    Code:
     //This program reads the <char> from the keyboard,  and then displays one of the following messages:/* 1. If <char> is a lower case letter, the message is 
               "The upper case character correspond to <char> is ___. "
       2. If <char> is an upper case letter, the message is
               "The lower case character correspond to <char> is ___. "
       3. If <char> is not a letter, the message is
               "<Char> is not a letter.                                                                      */
    
    
    
    
    #include <iostream>
    
    
    using namespace std;
    
    
    int main()
    {
    
    
      char letter;
    
    
      //prompt the user for letter
    
    
    
    
      cout << "Type in any letter:\n";
      cin  >> letter;
      cout << "\n";
    
    
      //print the appropriate message
    
    
      if (letter >= 65 && letter <=90) 
             cout << "The lower case character corresponds to '" << letter <<"' is " << (char)(letter + 32) <<".\n";
    
    
      else if (letter >= 97 && letter <=122) 
             cout << "The upper case character corresponds to '" << letter <<"' is " << (char)(letter - 32) << ".\n";
    
    
      else 
             cout << "The character '" << letter <<"' is not a letter.\n";
    
    
      system("pause");
    
    
      return 0;
    
    
    }

    Notice that I put
    char letter;
    However, the example answer given for the question number 3 @ C++ EXERCISES 2 is
    this http://www.doc.ic.ac.uk/~wjk/C++Intr...illerEA2-3.cpp.

    Can you please tell me why he/she alter the line to this??

    char letter = 'a';
    Thank you.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,456
    It is unnecessary since the first thing that you do to the variable is to read into it. It is typically good to initialise your variables, but in this case there is no real good default value to initialise it to. As such, to avoid using such a variable before reading into it, you should declare the variable as close as possible to the point where it is read into (or first used).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    Thanks for the reply but sorry, I don't really understand your explanation. First, I think I need to know what 'initialize' mean. Can you please explain what 'initialize' mean?

    Thank you.

  4. #4
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,409
    initialize is to give your variable a sensible value before using it - for reasons which should be obvious - or will be if you think about it / encounter enough bugs.
    Last edited by rogster001; 11-25-2012 at 02:19 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,208
    From an english language dictionary

    initialize, verb. To set variables, counters, or switches to their starting values.
    Right 98% of the time, and don't care about the other 3%.

  6. #6
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,409
    regarding your 'is it neccesary' question, in the light of initialisation - picture a scenario where var letter is used to determine a menu choice - however in this menu program there is a default selection of 'a' - so if the user opens the program and chooses to start a process rather than going to the options menu, then process will begin with option 'a' as a run parameter telling the process which path of execution to take, waht the calculations are and what is output etc, -
    if var letter was not initialised in this way in the scenario then what do you think might happen?
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  7. #7
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    Correct me if I'm wrong.

    From my understanding after take a few times reading your reply, here's what comes to surface of my understanding:

    Say, here's the menu in a restaurant: dish A , dish B , dish C and dish D.

    I set the initialization to dish C.

    So, if the customer want to eat immediately without going through the menu, by default, the customer will have to eat dish C.

    Am I right? =/

  8. #8
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,409
    yes

    in a restaurant offering a set 3 course 'plat du jour' but also does a la carte:

    start program
    initialise choice to c
    message from program:
    "Would you like to see the A la carte menu? Y/N"
    user enters N
    plat du jour (c) is served by default
    Last edited by rogster001; 11-25-2012 at 04:40 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  9. #9
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,638
    I have a problem with rogsters' example, since the variable he initialized and the choice he makes don't seem to be related. If choosing a default option is rude/not possible then you must choose a starting value that is not valid and catch mistakes later on, or arrange the code in a fashion that makes initialization not required.

  10. #10
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,409
    I agree it is a somewhat strained example - however - pedantry aside I was trying to think of something that illustrated the point wihtin the confines of the theme.

    for the OP here is a perhaps more useful look at what i am getting at - it is a very basic skeleton only and as our friend whiteflags points out would require a lot more substance in terms of validation etc - but anyway, the idea of this example is for you to compile it once as is, and choose option n when prompted - then remove the initialision of char choice -recompile - and again choose option n - and then see waht your final output looks like.

    Code:
    #include <iostream>
    
    void PrepareOrder(char choice)
    {
        std::cout << "Chef leGranFromage is preparing your food now\n\n";
    
        if(choice == 'p')
        {
            std::cout << "your order was the plat du jour\n\n";
        }
        else
        {
            std::cout << "your order was option: " << choice << "\n\n";
        }
    }
    
    char GetAlaCarte()
    {
        char poshOrder = 'Z';
    
        std::cout << "A La Carte Menu\n\n";
        std::cout << "(a) Badgers Snout dressed in a foam of dolphin's tears\n";
        std::cout << "(b) Sparrow with its legs tied toegether with a garnish of friacaseed snails\n";
        std::cout << "(c) Alphabet shapes with baked beans and chicken nuggets\n\n";
    
        std::cout << "Enter your order : ";
        std::cin >> poshOrder;
        std::cout << "\n\n";
    
        return poshOrder;
    
    }
    
    int main()
    {
        char choice = 'p'; //init
        char seeMenu = 'Z'; //me too - so i know there is a known value in this variable
    
        std::cout << "Welcome to Big Time Charlie's Bistro\n\n";
        std::cout << "We assume you are going to eat the plat du jour but just in case you have more money..\n";
        std::cout << "Would you like to see the expensive a la carte menu?  y / n \n";
        std::cin >> seeMenu;
        std::cout << "\n\n";
    
        if(seeMenu == 'y')
        {
            choice = GetAlaCarte();
        }
    
        PrepareOrder(choice);
    
    
        return 0;
    }
    Last edited by rogster001; 11-25-2012 at 05:22 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  11. #11
    Registered User
    Join Date
    Nov 2012
    Location
    Brunei
    Posts
    77
    I think I understand what initial mean now.

    rogster001's code was kind of a bit too complex for me though - is that some kind of code where you learn in your basic, or is that something you learn when you move into further chapter when learning C++?

    This kind of worrying me because I don't have any teacher except being dependent on the internet as a source of learning C++.

    Anyway, thank you. I now understand the basic concept of initials.

  12. #12
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,638
    As long as you understand what I said the examples can be as complex as you like. Keeping with the menu theme, imagine there are functions to serve specific orders.

    Here's an example that arranges the code in such a way that initialization is not an issue.
    Code:
    int choice = getChoice();
    while (choice != QUIT_CHOICE) {
       if (choice == 1) {
          ServePizza();
       }
       else if (choice == 2) {
          ServeBurger();
       }
       ...
       else if (choice == X) {
          ServeX();
       }
       /*else {
          BadChoice();
       }*/
       choice = getChoice();
    }
    This code implies that getChoice() is a function that will only return valid choices. But suppose you did not have such a convenient function. Well, if input completely fails on the first try you have the protection of BadChoice(); when it is uncommented. After the first choice you can continue use BadChoice(); to protect yourself.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21