微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C中的运算符优先级对于指针和迭代器是否不同?

下面的代码演示了这种差异:
#include <iostream>
#include <string>

int main()
{
        char s[] = "ABCD";
        std::string str(s);

        char *p = s;
        while(*p) {
                *p++ = tolower(*p);          // <-- incr after assignment
        }
        std::cout << s << std::endl;

        std::string::iterator it = str.begin(),end = str.end();
        while(it != end) {
                *it++ = tolower(*it);        // <-- incr before assignment ?
        }
        std::cout << str << std::endl;

        return 0;
}

它产生输出

abcd
bcd

如果我们分配赋值操作和增量运算符:

while(it != end) {
  *it = tolower(*it);        // <-- incr before assignment ?
  it++;
}

输出将如预期.

原始代码有什么问题?

$g++ --version
g++ (GCC) 3.4.4 (cygming special,gdc 0.12,using dmd 0.125)
copyright (C) 2004 Free Software Foundation,Inc.

解决方法

问题是operator =的参数的评估顺序是未指定的.这符合C标准5.2.2 / 8.考虑以下:
*it++ = tolower(*it);

等于

operator=( *it++,tolower(*it) );

现在*它可以在tolower(* it)之前计算,反之亦然.

原文地址:https://www.jb51.cc/c/116305.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐