YFROBOT创客社区

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1844|回复: 3
打印 上一主题 下一主题

宏: DATE , TIME , FILE , LINE

[复制链接]

签到天数: 22 天

[LV.4]偶尔看看III

跳转到指定楼层
楼主
发表于 2017-1-18 11:34:12 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 原始人 于 2017-1-18 11:34 编辑

宏定义的使用

一般情况下,C/C++编译器会内置几个宏,这些宏定义不仅可以帮助我们完成跨平台的源码编写,灵活使用也可以巧妙地帮我们输出非常有用的调试信息。

ANSI C标准中有几个标准预定义宏(也是常用的):
* __LINE__  :在源代码中插入当前源代码行号;
* __FILE__   :在源文件中插入当前源文件名;
* __DATE__  :在源文件中插入当前的编译日期
* __TIME__  :在源文件中插入当前编译时间;
* __STDC__  :当要求程序严格遵循ANSI C标准时该标识被赋值为1;
* __cplusplus :当编写C++程序时该标识符被定义。

编译器在进行源码编译的时候,会自动将这些宏替换为相应内容。

下面的代码,不仅展示了各个预定义宏的使用,还介绍了各个数据类型的长度。
[C] 纯文本查看 复制代码
#include <stdio.h>

int main(void) {
    int answer;
    short x = 1;
    long y = 2;
    float u = 3.0;
    double v = 4.4;
    long double w = 5.54;
    char c = 'p';;

    // __DATE__, __TIME__, __FILE__, __LINE__ 为预定义宏
    printf("Date : %s\n", __DATE__);
    printf("Time : %s\n", __TIME__);
    printf("File : %s\n", __FILE__);
    printf("Line : %d\n", __LINE__);
    printf("Enter 1 or 0 : ");
    scanf("%d", &answer);

    // 这是一个条件表达式
    printf("%s\n", answer?"You sayd YES":"You said NO");

    // 各种数据类型的长度
    printf("The size of int %d\n", sizeof(answer));
    printf("The size of short %d\n", sizeof(x));
    printf("The size of long %d\n", sizeof(y));
    printf("The size of float %d\n", sizeof(u));
    printf("The size of double %d\n", sizeof(v));
    printf("The size of long double %d\n", sizeof(w));
    printf("The size of char %d\n", sizeof(c));
}


输出结果:
[C] 纯文本查看 复制代码
Date : Feb 11 1997
Time : 13:51:31
File : white.c
Line : 20
Enter 1 or 0 : 1
You sayd YES
The size of int 4
The size of short 2
The size of long 8
The size of float 4
The size of double 8
The size of long double 8
The size of char 1
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|联系我们|YFROBOT ( 苏ICP备20009901号-2  

GMT+8, 2024-5-3 00:10 , Processed in 0.044366 second(s), 25 queries .

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表