Is it a good idea to have nested ternary operators in code? Warning: old style C code: BzCmp BzCompare (y, z) BigZ y, z; /* * Returns BZ_GT if Y > Z, * BZ_LT if Y < Z, * BZ_EQ otherwise. */ { return (BzGetSign (y) > BzGetSign (z) ? BZ_GT : BzGetSign (y) < BzGetSign (z) ? BZ_LT : BzGetSign (y) > 0 ? BnnCompare (BzToBn (y), BzGetSize (y), BzToBn (z), BzGetSize (z)) : BzGetSign (y) < 0 ? BnnCompare (BzToBn (z), BzGetSize (z), BzToBn (y), BzGetSize (y)) : BZ_EQ); }
Bz and bigZ just mean biginteger... it's that thing I needed help with yesterday: implement a bigint class
Please make this an if/else if/else tree. Nested ternaries are hard to read. I try to avoid ternary operators completely, unless it's a ridiculously simple case (and then only in *some* cases). I probably wouldn't even use it to implement signum(x). Maybe in a C macro, where the macro is so well-defined and perfectly working that no one would ever have to look at its implementation.
but they seem useful for writing return one-liners, like the above code to compare two bigints.
Yes, they are useful for writing code. But they are not useful for reading code. Write code to be read.
this is gud habit of writing the program...... LOC's are reduced using this programming and efficiecy will be increased
I believe readabilty and understandability takes precedence over LOCs. If a single line of code can more effectively represent a procedure than 100 lines of code (compare hundreds of C lines to perhaps 3 SQL or python lines), then I'd go with that. However, if someone writes an OS or even a simple strcpy procedure in a few lines, it will usually be difficult to understand by others, unless the author spreads out the procedure into multiple lines, uses effective names in his code, effective comments, etc.
Join our real-time social learning platform and learn together with your friends!