Menu
CoddyTech

布尔值与分支

Coddy 面向 Go 开发者的 C 课程的第 7 课,共 48 课。

Go 要求条件必须是 bool 类型。C 接受标量真值测试,因此指向空字符串的指针在非 null 时为真;不要把 Go 的 len 语义翻译成指针测试,而应显式检查字符串是否为空。

零值和 null 指针在条件中为假。指向空字符串的指针仍然不是 null。

Go 示例

package main
import ("fmt")

func main(){
s:="";fmt.Println(len(s)==0)
}

Go 输出:

true

C 示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
const char *s=""; printf("%s\n",s?"true":"false");
return 0;
}

C 输出:

true
challenge icon

挑战

简单

输入为负数时返回 -1,输入为零时返回 0,输入为正数时返回 1。

编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,因为该文件会直接调用它。不要添加另一个 main。除非任务明确检查取值范围,否则所有数值任务测试数据都足够小,不会溢出。只打印指定的输出;如果有显示驱动程序,它会负责解析输入和生成输出。

亲手试试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n=0;if(scanf("%d",&n)!=1)return 1;printf("%d\n",sign_of(n));return 0;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 C中的所有课

自己练习: C 在线编译器