如何与numeric_limits <int64_t> :: min()比较

时间:2015-10-26 10:47:01

标签: c++ stl int64 uint64 numeric-limits

考虑标志(<Page.Resources> <Storyboard x:Name="FlipBottomStoryboard"> <DoubleAnimation Duration="0:0:1.1" To="-80.9" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)" Storyboard.TargetName="grid" d:IsOptimized="True"/> </Storyboard> </Page.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition/> <RowDefinition/> <RowDefinition Height="2*"/> </Grid.RowDefinitions> <Grid Grid.RowSpan="2"> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition/> </Grid.RowDefinitions> <Rectangle Stroke="Black" Fill="#FF4E608F"/> </Grid> <Grid x:Name="grid" Grid.Row="2" Grid.RowSpan="2" Canvas.ZIndex="1"> <Grid.Projection> <PlaneProjection CenterOfRotationX="0" CenterOfRotationY="0"/> </Grid.Projection> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="2*"/> </Grid.RowDefinitions> <Interactivity:Interaction.Behaviors> <Core:EventTriggerBehavior EventName="Tapped"> <Media:ControlStoryboardAction Storyboard="{StaticResource FlipBottomStoryboard}"/> </Core:EventTriggerBehavior> </Interactivity:Interaction.Behaviors> <Rectangle Fill="#FF3DDA24" Stroke="Black" Grid.Row="1"/> </Grid> <Rectangle Stroke="Black" Grid.Row="1" Grid.RowSpan="2"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="#FFA65757"/> <GradientStop Color="#FF0A2E26" Offset="0.966"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> </Grid> +1)是已知的,并且有一个代码可以解析无符号整数。无符号整数可以等于-1。如何正确比较而不触发未定义的行为?

-numeric_limits<int64_t>::max()

1 个答案:

答案 0 :(得分:3)

正如Holt所说,你实际上是假设2的补码算术。因此,您可以将-min替换为max+1

if(result == uint64_t(numeric_limits<int64_t>::max()) + 1)

这可以避免在否定最小值时产生的未定义行为(有符号整数溢出)。

验证您的系统确实使用2的补码(取决于您希望遵守C ++标准的严格程度)可能是个好主意。这可以通过将-maxmin进行比较来实现:

if (numeric_limits<int64_t>::max() + numeric_limits<int64_t>::min() == 0)
{
    // If not two's complement:
    // Too large absolute value == error, regardless of sign
    return false;

    // on all sane (2's complement) systems this will be optimized out
}

minmax之间不存在其他关系;这是here解释的。