C语言 c函数中的指针“未使用计算值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4347684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:17:13  来源:igfitidea点击:

pointer "value computed is not used" in c function

cpointersgcc

提问by Andreas W. Wylach

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?

我编写了一个函数,可以按要求的长度缩短字符串(单词的句子)。我不希望句子的剪辑恰好在一个单词的中间。所以我跳过 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 = '
p--;
'; /* 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)"

我在开发机器上的编译器是“gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)”

回答by casablanca

The warning is due to the *(dereference) -- you aren't using the dereferenced value anywhere. Just make it:

警告是由于*(取消引用) - 您没有在任何地方使用取消引用的值。只要做到:

            *p--;

and the warning should go away.

并且警告应该消失。

回答by James McNellis

*p--is the same as *(p--).

*p--与 相同*(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.

减量被评估,然后你取消引用它的结果。你实际上并没有对这个结果做任何事情,因此是警告。如果你只是说 ,你会得到同样的警告*p

回答by pmg

You just do this for the side-effect

你这样做只是为了副作用

##代码##
  • Side-effect: decrement p
  • Value of expression: value pointed to by p
  • 副作用:减少 p
  • 表达式的值:p 指向的值

The compiler is warning you the value of the expression is not used :-)

编译器警告您未使用表达式的值:-)