zoukankan      html  css  js  c++  java
  • c语言中宏定义和常量定义的区别

      他们有共同的好处就是“一改全改,避免输入错误”哪两者有不同之处吗?有的。

      主要区别就在于,宏定义是在编译之前进行的,而const是在编译阶段处理的

    宏定义不占用内存单元而const定义的常量占用内存单元

    宏定义与const常量有着相同的作用-----用一个符号表示数据,但是,有些书上说定义数组常量不能用const,经过测试也是可以的,环境是vs2015

      常量定义定义数组的长度

      const int N=66;

      int arr[N];

    有的书上说是错误的,但经过我在vs2015上测试是可以的

      宏定义定义数组的长度

      #define N 66

      int arr[N];

    带参数的宏定义

    格式:

    #define 宏名(参数列表) 要更换的内容

    #define SUM(a,b) a+v

    程序代码如下:

    S=SUM(6,8);

    将宏定义中的a和b分别替换成6和8,替换后的代码是:

    s=6+8;

    #define没有数据类型,只是单纯的替换

    #include "stdafx.h"
    #include<stdlib.h>
    #define add(a,b) (a)>(b)?(a):(b)
    int main()
    {   
        printf("%s", add("abc", "bcd"));
        system("pause");
        return 0;
    }
    #include "stdafx.h"
    #include<stdlib.h>
    #define add(a,b) (a)>(b)?(a):(b)
    int main()
    {
        printf("%d", add(1+2, 3+4));
        system("pause");
        return 0;
    }

    这些都是可以的

    所以一般建议使用函数不建议使用宏定义

     宏定义交换两个数值:

    #include<stdio.h>
    #include<stdlib.h>
    #define swap1(a,b){a=a+b;b=a-b;a=a-b;}
    #define swap2(a,b){a=a^b;b=a^b;a=a^b;}
    int main(){
        int a=5;
        int b=6;
        printf("Before convert: a=%d;b=%d
    ",a,b);
        swap1(a,b);
        printf("After convert:     a=%d;b=%d
    ",a,b);
        int c=7;
        int d=8;
        printf("Before convert: c=%d;d=%d
    ",c,d);
        swap2(c,d);
        printf("After convert:    c=%d;d=%d
    ",c,d);
    }

     

  • 相关阅读:
    【转】Visual studio 快捷键大全
    C++ 中的权限控制
    论C++11 中vector的N种遍历方法
    c++ 模板仿函数初探
    OBS (open boardcast server)结构分析
    OpenCV学习笔记:opencv_core模块
    [转]C++ new操作符详解
    进程已经被attach debug,如何解除其debug权限?
    dll 在进程中怎么区分的
    树状数组学习笔记
  • 原文地址:https://www.cnblogs.com/blueberry006/p/7822347.html
Copyright © 2011-2022 走看看