Ternary operator: odd behaviour when combined with operator +

Posted on 2007-10-02
Last Modified: 2010-04-01
Ah hello.

I put the following code in a program I am working on and was surprised at the result:

      CString s ( _T("This is a long string") );
      int n = 1 + ( s.GetLength() ) ? 1 : 0;

n is 1; why is it not 2?


      int n = 1 + ( s.GetLength() > 0 ) ? 0 : 1;

results in n being 0.

I might be having a moment of madness here, but what is going on??

Question by:mrwad99
    LVL 39

    Accepted Solution

    The problem is that the ?: operator takes (1 + ( s.GetLength() ) ) as left operand. So, the left operand is always true.

        int n = 1 + ( s.GetLength()? 1 : 0 ) ;

    That would give the expected result.

    Regards, Alex
    LVL 19

    Author Comment

    Excellent.  I see now.

    Thanks :)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
    Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
    The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
    The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now