Cpp-Language

ทดสอบ:## operator

/***************************************************
* Author : o2mini
* Project : Tutorial Examples
* Creation Date : October 2004
* Description : ทดสอบการใช้งาน ## operator
***************************************************/
#include <stdio.h>
#definejoin( a, b )(a##b)

void main ( void )
{
intiResult ,ab = 1;
iResult= join( a, b );
printf ("iResult = %d\n", iResult );
}

ทดสอบ:# operator

/****************************************************
* Author : o2mini
* Project : Tutorial Examples
* Creation Date :October 2004
* Description : ทดสอบการใช้งาน # operator
***************************************************/
#include <stdio.h>
#define toString( Token ) #Token

void main( void )
{
char *myToken = "Hello";
printf("variable name = %s\n", toString( myToken ) );
printf("variable value = %s\n", myToken );
}

ปัญหาอย่างหนึ่งของการใช้ Reserve Word#define ก็คือการไม่แจ้ง Error Message เมื่อเกิดการ กำหนดซ้ำขึ้น ปัญหานี้ก่อให้เกิด Logic Error ขึ้น เพราะฉะนั้นถ้าเลี่ยงได้ก็ควรเลี่ยงเพื่อไม่ให้เกิดปัญหาภายหลังCoding Program เรียบร้อยแล้ว ยกเว้นผู้เชี่ยวชาญแล้ว
โดยในกรณี ต้องการตั้ง Constants พยายามใช้ enum or const แทนที่การใช้ #define เช่น

#define CGREEN 1 // แย่
const int cGreen = 1 ; // ดี
enum ( cGreen = 1 ) ; // ดีกว่า
enum Color ( red, blue, green ); // ดีที่สุด

และกรณี ต้องการตั้ง Macros Function ควรใช้ inline

#define Square ( x ) ( ( x ) * ( x ) )

แทนที่การใช้ #define เช่น แทนที่ด้วย inline function

inline long Square ( short x )
{
return ( ( long ) x * ( long ) x ) ;
}