const std = @import("std");
const expect = std.testing.expect;
const eq = std.testing.expectEqual;
fn signedDiv(a: i32, b: i32) i32 { return @divTrunc(a, b); }
fn signedRem(a: i32, b: i32) i32 { return @rem(a, b); }
test "arithmetic signed divisions remainder and saturation" {
const a: i32 = 5;
const b: i32 = 3;
try eq(@as(i32, 8), a + b);
try eq(@as(i32, 2), a - b);
try eq(@as(i32, 15), a * b);
try eq(@as(i32, 1), signedDiv(a, b));
try eq(@as(i32, 2), signedRem(a, b));
try eq(@as(i32, -1), signedDiv(-5, 3));
try eq(@as(i32, -2), @divFloor(@as(i32, -5), @as(i32, 3)));
try eq(@as(i32, -2), signedRem(-5, 3));
try eq(@as(i32, 1), @mod(@as(i32, -5), @as(i32, 3)));
try eq(@as(u8, 0), @as(u8, 255) +% 1);
try eq(@as(u8, 255), @as(u8, 255) +| 1);
}
test "all relational logical and bitwise operators" {
const a: i32 = 5;
const b: i32 = 3;
try expect(!(a == b) and a != b and a > b and !(a < b) and a >= b and !(a <= b));
const yes = true;
const no = false;
try expect(!(yes and no) and (yes or no) and !no);
try eq(@as(i32, 1), a & b);
try eq(@as(i32, 7), a | b);
try eq(@as(i32, 6), a ^ b);
try eq(@as(i32, -6), ~a);
try eq(@as(i32, 10), a << 1);
try eq(@as(i32, 2), a >> 1);
}
test "assignment sequence increments concat and precedence" {
var a: i32 = 5;
a += 3; try eq(@as(i32, 8), a);
a -= 3; try eq(@as(i32, 5), a);
a *= 3; try eq(@as(i32, 15), a);
a = @divTrunc(a, 3); try eq(@as(i32, 5), a);
a = @mod(a, 3); try eq(@as(i32, 2), a);
a &= 3; try eq(@as(i32, 2), a);
a |= 3; try eq(@as(i32, 3), a);
a ^= 3; try eq(@as(i32, 0), a);
a <<= 1; a >>= 1; try eq(@as(i32, 0), a);
var u: u8 = 12; u /= 3; u %= 3; try eq(@as(u8, 1), u);
a += 1; a -= 1; try eq(@as(i32, 0), a);
const concatenated = "blue" ++ "sky";
try std.testing.expectEqualStrings("bluesky", concatenated);
try eq(@as(i32, 11), @as(i32, 5) + 3 * 2);
try eq(@as(i32, 16), (@as(i32, 5) + 3) * 2);
try expect(5 > 3 and 3 > 2);
try expect(!(!(5 > 3) and 3 > 2));
const empty: ?u8 = null; try eq(@as(u8, 9), empty orelse 9);
}
本例需在 Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows / Zig0.14.1 / Debug模式;0.15+及其它系统另验
入口文件:projects/zig-lab/zig-operators.zig
预期结果与验证条件观察提示
- 该文件全部具名测试真实通过,未跳过或把编译成功当成执行完成。
- 具体输入、分支及数值由本章源码的expect/eq/expectError逐项核对;源码哈希与运行记录对应。
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联14章) · 含当前章节或实例 · mbskycom202611a544.zip