C/C++ Basics–>about #define, const

來源:互聯網
上載者:User

1.
    In C programming, the normal use of #define is to declare an constant vairiable. But it's been replaced by const.
C: #define X 100   ----> C++: const int x=100;

2.
    #define can also define Macro with parameters. But its functionality can also be replaced by inline function with C++
C: #define MAX(a,b) ((a)>(b)?(a):(b))
C++: inline int max(int a,int b){ return a>b?a:b;}

3.
    #define is most used in conditional compling. the conditional compling instruction includes:#if,#else,#endif,#ifdef,#ifndef,#undef.
    it always be used to avoid the head file being referenced more than once.
    eg.
    #ifndef NULL
        #define NULL ((void*)0)
    #endif

    #ifndef _myheadfile_h
        #define _myheadfile_h
    #endif

 

4.const

const有很多作用,主要可以有以下幾種:

1. const int x=10; //定義一個常量 ,該常量分配在靜態儲存區

2 const int *p;//p是一個常量pointer,只能指向常量,因此不能進行左操作

3 int f(const int x) //表示f函數中不能修改x的值

4 int f(int x) const //這種主要用在類的成員函數的修飾上,表示該函數不會修改類的成員變數。
    

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.