Thread: Ways to Write IF Statements...

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

    Ways to Write IF Statements...

    Just like the topic says, I was wondering if there are any different ways to write IF statements besides the following:

    if(x > 0)
    {
    cout << "X is Greater than 0";
    }
    else
    {
    cout << "X is Less than 0";
    }

    OR...

    cout << (x > 0 ? "X is Greater than 0" : "X is Less than 0");

    OR...

    x > 10 ? cout << "It is Greater than 0" : cout << "It is Below 10";

    Thanks for the Help!!

    Mike

  2. #2
    Registered User Engineer's Avatar
    Join Date
    Oct 2001
    Posts
    125

    Thumbs down

    Not as far as I know. This is it.

    You do have a problem in your example:

    if x > 0 then you print "x is bigger than 0"

    else you print "x is smaller than 0"

    But in the case of your else x could be either smaller of equal to 0.
    1 rule of the Samurai Code: if you have nothing to say, don't say anything at all!

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    403

    else if, switch, etc.

    i'm not sure if this is what you're looking for but this is another way:

    switch(x<0)
    {
    case true:
    cout << "X is negative";
    case false:
    cout << "X is positive";
    }

    or if you wanted to test for zero separately you could do

    if(x < 0)
    cout << "X is negative";
    else if(x ==0)
    cout << "X is zero";
    else
    cout << "X is positive";


    hope that answered your question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with fstream, one variabile for write and read
    By Smjert in forum C++ Programming
    Replies: 3
    Last Post: 02-03-2009, 10:19 PM
  2. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  3. Efficiency of case statements
    By Yasir_Malik in forum C Programming
    Replies: 26
    Last Post: 05-23-2006, 11:36 AM
  4. Reroute where programs write to
    By willc0de4food in forum C Programming
    Replies: 7
    Last Post: 09-21-2005, 04:48 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM