zoukankan      html  css  js  c++  java
  • C++中的预处理器

    C++的预处理器预处理器指令包括如下12个。

    #if         #else      #elif         #endif       #ifdef      #ifndef     #undef

    #error    #line      #pragma   #include    #define 

    第一行7个就是控制语句,重点在后面5个。

    1. #define 

    #define macro-name char-sequence 

    #define定义了一个标识符和一个字符序列。每次在源程序中遇到该标识符就用定义的字符序列替代它。

    标识符被即宏名;替换过程即宏替换。  

    #define ONE 1
    #define TWO ONE + ONE
    #define PI 3.14
    #define ERRMSG "ERR!!!"
    //.......
    printf(ERRMSG);

    宏定义中如果字符序列超过一行,可以在末尾用反斜杠续行

    #define LONGSTRING "this is a very very \
                        very very.......\
                        
    long string"

    宏名不一定要大些,但C++程序员大都习惯用大些字母。并且习惯常将所有的宏集中在一或多个单独的头文件中。 

    宏名可以有变元。遇到宏名时,其定义中所用的变元均由实际程序中的变元来代替。这一点很像inline函数。但define的对象,编译器只是做简单的字符替换,其他操作例如类型检查。应尽量使用inline来代替define。

    #include <stdio.h>
    #define ABS(a) (a)<0? -(a) :(a)  // 这里的括号很重要

    int main(void)
    {
      printf(
    "abs of -1 and 1: %d %d", ABS(-1), ABS(1));
      
    return 0
    }

      

    #error

    #error error-message // error message不用双引号括起来

     #error主要用在调试中,强迫编译器停止编译 。错误信息会随编译的其他信息一同显示。

    #include

    #include <xx.h>  //使用编译器创建者定义的方式查找
                     
    //通常是从项目定义的众多包含目录下开始
    #include "xx.h"  //使用其他实现所定义的方式查找
                     
    //通常是从当前工作目录开始,
                     
    //如未找到,则按<>的规定继续查找

    #line 

    #line number "filename"

    用来改变__LINE__和__FILE__的内容。这两个标识符是编译器中预先定义的标识符。 

    前者表示已编译的代码行数,后者是一字符串,包含已编译的源文件名。 

    number为__LINE__的新值,filename为任意有效的文件名标识符,是__FILE__ 的新值。

    #pragma

    #pragma是一个实现时定义的指令,用它向编译器传送各种指令。例如

    #pragma once

      

    #和##预处理器运算符

    #和##与#define一起使用。

    #,stringize运算符,使它后面的变元转换成带引号的串。 

    #include <stdio.h>
    #define mkstr(s) #s
    int main(void)
    {
      
    //I like C++ 就是mkstr宏中的s,
      
    //预处理器将这一大串加上引号变成"I like C++"
      printf(mkstr(I like C++)); 
      
    return 0 ;
    }

    ##,pasting运算符,用于连接两个符号。 

    #include <stdio.h>
    #define concat(a,b) a##b
    int main(void)
    {
      
    int xy = 10;
      printf(
    "%d", concat(x,y)); //预处理器将其变成打印xy的值
      return 0 ;
    }

    预定义的宏名

    __LINE__      __FILE__    __DATE__     __TIME__    __STDC__    __cplusplus

  • 相关阅读:
    Permutation Sequence
    Anagrams
    Unique Binary Search Trees II
    Interleaving String
    Longest Substring Without Repeating Characters
    Sqrt(x)
    Maximum Product Subarray
    Jump Game II
    Container With Most Water
    C结构体的初始化和赋值
  • 原文地址:https://www.cnblogs.com/mumuliang/p/1886891.html
Copyright © 2011-2022 走看看