使用cout进行计算时的未定义行为

时间:2015-11-11 07:41:21

标签: string cout

我有一个空字符串

var App = {
    ...
};

App.init();

Quagga.onProcessed(function(result) {
    ...
};

Quagga.onDetected(function(result) {
    ...
}

angular.module( ...
        // Read files into angular
            .directive('file', [function () {
                return {
                    scope: {
                        myFile: '=',
                        myFileType: '@'
                    },

                    link: function (scope, element, attributes) {
                        element.bind('change', function (changeEvent) {
                            scope.$apply(function () {
                                scope.myFile = changeEvent.target.files[0];

                                if (scope.myFileType != null && scope.myFileType !== undefined && scope.myFileType == "barcode") {
                                    App.decode(URL.createObjectURL(scope.myFile));
                                }
                            });
                        });
                }
            }
        }])

它打印2 ^ 32-1,即string A=""; cout<<A.size()-1;

但预期答案显而易见4294967295

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以通过将其转换为int

来获得预期的输出
cout << int(A.size()-1);

string :: size()返回size_t,通常定义为unsigned int。 这就是它的印刷方式。 通过将其转换为int,我们可以将其解释为signed int。

答案 1 :(得分:0)

string :: size返回size_t,这是一个无符号整数类型(与成员类型string :: size_type相同)。所以答案是正确的。你想要的是签名积分:

cout << static_cast<int>(A.size())-1;

此处投射是安全的,因为显然尺寸小于INT_MAX。