import stdio import t, c # ============================================================ # 简单指针 + 逻辑测试 # ============================================================ def ptr_test() -> int: # 逻辑测试:if 语句 x: int = 10 if x: stdio.printf("if: x is truthy\n") if 1 == 1: stdio.printf("if: 1==1 is truthy\n") # While 循环 + 累加 i: int = 0 total: int = 0 while i < 5: total = total + i i = i + 1 stdio.printf("while: total=%d i=%d\n", total, i) # For 循环 for j in range(5): stdio.printf("for: j=%d\n", j) # Break 测试 for k in range(10): if k == 3: break stdio.printf("break: k=%d\n", k) # Continue 测试 for m in range(5): if m == 2: continue stdio.printf("continue: m=%d\n", m) # 布尔运算 and(短路求值) if x > 5 and x < 100: stdio.printf("bool: x>5 and x<100 is true\n") # 布尔运算 or(短路求值) if x > 100 or x > 5: stdio.printf("bool: x>100 or x>5 is true\n") # ============================================================ # 指针 + c.Deref / c.DerefAs 测试 # ============================================================ # 字符串遍历: while c.Deref(p) != 0 s: str = "hello" sp: str = s slen: int = 0 while c.Deref(sp) != 0: slen = slen + 1 sp = sp + 1 stdio.printf("ptr: len(hello)=%d\n", slen) # c.DerefAs 写入字符(使用 c.Addr 获取栈变量地址,字符串字面量是只读的) v: int = 65 # 'A' px: str = c.Addr(v) c.DerefAs(px, 88) # *px = 88 stdio.printf("ptr: after DerefAs v=%d\n", v) # 遍历字符串并累加字符值 p2: str = "ABC" total_ch: int = 0 while c.Deref(p2) != 0: total_ch = total_ch + c.Deref(p2) p2 = p2 + 1 stdio.printf("ptr: sum(A,B,C)=%d\n", total_ch) # ============================================================ # c.Load 测试: *a = *b(加载源指针的值,存储到目标指针) # ============================================================ # 基本复制: v2 = v1 v1: int = 42 v2: int = 0 c.Load(c.Addr(v2), c.Addr(v1)) stdio.printf("ptr: c.Load v2=%d (expected 42)\n", v2) if v2 != 42: stdio.printf("[FAIL] c.Load expected 42 got %d\n", v2) return 1 # 覆盖已有值: v3 = v4 v3: int = 100 v4: int = 200 c.Load(c.Addr(v3), c.Addr(v4)) stdio.printf("ptr: c.Load overwrite v3=%d (expected 200)\n", v3) if v3 != 200: stdio.printf("[FAIL] c.Load overwrite expected 200 got %d\n", v3) return 1 # 验证源不被修改: v5 保持原值 v5: int = 999 v6: int = 0 c.Load(c.Addr(v6), c.Addr(v5)) stdio.printf("ptr: c.Load src unchanged v5=%d v6=%d (expected 999, 999)\n", v5, v6) if v5 != 999: stdio.printf("[FAIL] c.Load src changed v5=%d\n", v5) return 1 if v6 != 999: stdio.printf("[FAIL] c.Load dst expected 999 got %d\n", v6) return 1 return 0