Thread: Initializing variables

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    9

    Angry Initializing variables

    I set a letter

    char ch;
    Int r;

    and when I try to use them in an if-

    cin >> ch;
    if (ch==r)
    cout << "blah blah blah"<<endl

    every time I do this it gives me warning

    warning C4700: local variable 'r' used without having been initialized

    and the darn thing wont work, it just exits the program.

    What do I do?

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    give r a value, say 65 or 92 or whatever.

    int r = 65;
    if(ch == r)
    {...

    r = 92;
    if(ch == r)
    {...

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > local variable 'r' used
    That's this line
    > if (ch==r)

    > without having been initialized
    That's this line
    > Int r;

    Quite simple really, there is no assignment TO r before you try and read FROM r
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    i hope you are using

    int

    and not

    Int

    for one. (there is a difference).

    But your warning is because you never set the value 'r' to anything.

    You enter a character. Then you say if this character is equal to a value that I haven't even defined, output this.

    If you initialized the value of r like

    int r=0;

    Your warning would go away. The thing is, you would never see your cout << "blah" because any character you enter will never be zero.

    Examine this.

    int main ()
    {

    char ch;
    char other='A'; // note you can combine 'like' instantiations

    cout << "Try to guess the letter: ";
    cin >> ch;

    if (ch==other)
    cout << "YOU GUESSED IT!";
    else
    cout << "NOPE. TRY AGAIN!";

    return 0;
    }
    Blue

  5. #5
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    I need to learn to type even faster...
    Blue

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  2. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  3. initializing structure variables
    By cs32 in forum C Programming
    Replies: 2
    Last Post: 04-11-2008, 05:33 PM
  4. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 11:07 PM
  5. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM