Dear all,

How would you best explain the below code fragment?

return (i == 0) ? strNum : strNum.substring(i);

Thanks alot!

Recommended Answers

All 3 Replies

It's a simple ternary operator

condition ? true result : false result

so if i==0 it will return strNum, otherwise it returns strNum.substring(i).

Dear all,

How would you best explain the below code fragment?

return (i == 0) ? strNum : strNum.substring(i);

Thanks alot!

if (i==0) is true, then return strNum, otherwhile return strNum.substring(i)

Rewriting with if:

if (i == 0) return strNum; else return strNum.substring(i);

But the substring with the 0 parameter already returns the whole string unchanged, so it's really:

return strNum.substring(i);

And I think it's wiser to leave for the programmer that wrote the substring function to decide if it's faster to test for special values to possibly jump through the computation or it's faster to start it asap.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.