• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 204
  • Last Modified:

Ternary operator: odd behaviour when combined with operator +

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?

Interestingly,

      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??

TIA
0
mrwad99
Asked:
mrwad99
1 Solution
 
itsmeandnobodyelseCommented:
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
0
 
mrwad99Author Commented:
Excellent.  I see now.

Thanks :)
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now