C 将数据塞入单个语句
以我拥有的以下单词计数程序为例,其中一个单词(天真地)在C 将数据塞入单个语句,c,C,以我拥有的以下单词计数程序为例,其中一个单词(天真地)在空格之间被视为alnums: #include<stdio.h> #include<ctype.h> #include<stdbool.h> int main(void) { // grab a segment of text until EOF int current_char; int num_words=0, num_chars=0, num_lines=0; // ign
空格之间被视为alnum
s:
#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
int main(void)
{
// grab a segment of text until EOF
int current_char;
int num_words=0, num_chars=0, num_lines=0; // ignore whitespace
bool in_word;
printf("Enter your text here:\n");
while ((current_char=getchar()) != EOF)
{
if (current_char == '\n')
in_word ? num_words++, num_lines ++, in_word-- : num_lines++;
else if (isalnum(current_char))
num_chars ++, in_word=true;
else if (isspace(current_char))
in_word ? num_words++, in_word-- : ' ';
}
if (in_word) num_words ++;
printf("\nChar Count: %d | Line count: %d | Word count: %d\n", num_chars, num_lines, num_words);
}
这对我来说似乎更可读,也更容易理解,但我经常会在C中看到长的一行程序,因此我想知道为什么一个选项可能会被使用而不是另一个
例如,这里有一行代码,看起来太长了,我很难理解:
if (!gsets)
ereport(ERROR,
(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
errmsg("too many grouping sets present (maximum 4096)"),
parser_errposition(pstate,
qry->groupClause
? exprLocation((Node *) qry->groupClause)
: exprLocation((Node *) qry->groupingSets))));
评论不用于扩展讨论;这段对话已经结束。这里应用的主要经验法则是,哪一条更易读,更容易修改?用多种方法编写同一代码,然后评估每种方法的优缺点,包括可读性,通常是有益的。
if (!gsets)
ereport(ERROR,
(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
errmsg("too many grouping sets present (maximum 4096)"),
parser_errposition(pstate,
qry->groupClause
? exprLocation((Node *) qry->groupClause)
: exprLocation((Node *) qry->groupingSets))));