patterncMinor
Validating a tab-delimited string
Viewed 0 times
tabdelimitedstringvalidating
Problem
This code checks if string has correct format for passing to struct. Correct format needs to be
I wrote alternative version as well (in comments). Which one is more preferable?
How is the correct form to write nested ternary operator
[123456789'\t'First Name'\t'Last Name'\t'City]. I didn't know how to enter tabs, so I used '\t'. I use them to separate different word blocks so e.g. first and middle name can be read to a first name in struct.I wrote alternative version as well (in comments). Which one is more preferable?
How is the correct form to write nested ternary operator
int checkString(char *string, int len)
{
char *ch;
int flag = FALSE;
int i = 0;
ch = string;
i = 0;
/*
while (ch[i] && ch[i] != '\t') {
if (isdigit(ch[i])) {
if (++i == len) {
flag = ch[i] == '\t' ? TRUE : FALSE;
}
} else { ch++; }
}
*/
/* ID code needs to be 11 digits */
for (i = 0; ch[i] && ch[i] != '\t';
isdigit(ch[i]) ?
flag = ++i == len ? // while true
ch[i] == '\t' ? TRUE : FALSE // while true
: FALSE
: *ch++);
/* Three tabs is correct */
if (flag) {
for (i = 0; ch[i];
ch[i] == '\t' ?
flag = ++i == 3 ? TRUE : FALSE
: *ch++);
}
return flag;
}Solution
Avoid nested ternary operators. It hardly ever improves readability over proper if-else conditions.
When the boolean values
This is equivalent and simpler:
When a condition gets complicated, another technique is to extract the complex boolean expression to a helper method with a good descriptive name.
When the boolean values
true and false are involved, often there's simply no need for tensors at all, like in this example:flag = ch[i] == '\t' ? TRUE : FALSE;This is equivalent and simpler:
flag = ch[i] == '\t';When a condition gets complicated, another technique is to extract the complex boolean expression to a helper method with a good descriptive name.
Code Snippets
flag = ch[i] == '\t' ? TRUE : FALSE;flag = ch[i] == '\t';Context
StackExchange Code Review Q#121837, answer score: 6
Revisions (0)
No revisions yet.