指针“不使用计算的值”在c函数中
我编写了一个函数,可以按照请求的长度缩短字符串(单词的句子)。我不希望句子的剪切恰好位于单个单词的中间。所以我向后跳 n 个字符,直到到达一个空格并在那里剪切句子字符串。 我的问题并不是真正的问题,编译我的函数会发出一条警告,提示“警告:未使用计算值”,请参阅代码中的注释行。但该功能按预期工作。 所以要么我是盲目的,要么我在我的项目上坐得太久了,实际上我不明白这个警告。有人可以指出我该功能的缺陷吗?
char *
str_cut(char *s, size_t len) {
char *p = NULL;
int n = 3;
p = s + len;
if (p < (s + strlen (s))) {
/*
* do not cut string in middle of a word.
* if cut-point is no space, reducue string until space reached ...
*/
if (*p != ' ')
while (*p != ' ')
*p--; // TODO: triggers warning: warning: value computed is not used
/* add space for dots and extra space, terminate string */
p += n + 1;
*p = '\0';
/* append dots */
while (n-- && (--p > s))
*p = '.';
}
return s;
}
我在开发机器上的编译器是“gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)”
I wrote a function that that shortens a string (sentence of words) at requested length. I do not want that a the cut of the sentence happens to be in middle of a single word. So i skip back n chars until I reach a space and cut the sentence string there.
My problem is not really a problem, compiling my function spits out a warning that says "warning: value computed is not used", see the commented line in the code. The function works as expected though.
So either I am blind, or I am sitting to long on my project, actually I do not understand that warning. Could anybody please point me the flaw in the function?
char *
str_cut(char *s, size_t len) {
char *p = NULL;
int n = 3;
p = s + len;
if (p < (s + strlen (s))) {
/*
* do not cut string in middle of a word.
* if cut-point is no space, reducue string until space reached ...
*/
if (*p != ' ')
while (*p != ' ')
*p--; // TODO: triggers warning: warning: value computed is not used
/* add space for dots and extra space, terminate string */
p += n + 1;
*p = '\0';
/* append dots */
while (n-- && (--p > s))
*p = '.';
}
return s;
}
My compiler on the development machine is "gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该警告是由于
*
(取消引用)引起的 - 您没有在任何地方使用取消引用的值。只要做到这一点:警告就会消失。
The warning is due to the
*
(dereference) -- you aren't using the dereferenced value anywhere. Just make it:and the warning should go away.
*p--
与*(p--)
相同。计算减量,然后取消引用其结果。您实际上并没有对这个结果做任何事情,因此会出现警告。如果您只是说
*p
,您会收到相同的警告。*p--
is the same as*(p--)
.The decrement is evaluated, then you dereference the result of that. You don't actually do anything with that result, hence the warning. You would get the same warning if you just said
*p
.您这样做只是为了副作用
编译器警告您未使用表达式的值:-)
You just do this for the side-effect
The compiler is warning you the value of the expression is not used :-)