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);
    }

     

  • 相关阅读:
    FileManager(文件管理类)
    XE6 IntraWeb.v14.0.32安装及破解指南
    在应收应付系统凭证做冲销后,如何取消冲销?
    delphi将图片保存到SQL数据库和读取图片
    去掉cxgrid 中的过滤下拉箭头
    CxGrid 分组以后自动排序了,可以禁止自动排序吗
    最简单解决CHM文件无法显示的办法
    用友T3、T6常见问题
    SQL2005还原数据库3154错误
    cxGrid 怎样才能让不自动换行 WordWrap:=false
  • 原文地址:https://www.cnblogs.com/blueberry006/p/7822347.html
Copyright © 2011-2022 走看看