Object-C中的#和##操作符(The # and ##Operator)

1 篇文章 0 订阅
1 篇文章 0 订阅

The # Operator

If you place a # in front of a parameter in a macro definition, the preprocessor creates

a constant C-style string out of the macro argument when the macro is invoked. 

For example, the definition

#define str(x) # x

causes the subsequent invocation

str (testing)

to be expanded into

”testing”

by the preprocessor.The printf call

printf (str (Programming in Objective-C is fun.\n));

is therefore equivalent to

printf ( ”Programming in Objective-C is fun.\n ”);

The preprocessor inserts double quotation marks around the actual macro argument.

The preprocessor preserves any double quotation marks or backslashes in the argument. So

str (“hello”)

produces

”\”hello\ ””

A more practical example of the # operator might be in the following macro definition:

#define printint(var) printf (# var “ = %i\n ”, var)

This macro is used to display the value of an integer variable. If countis an integer

variable with a value of 100 , the statement

printint (count);

is expanded into this:

printf ( ”count”“ = %i\n ”, count);

The compiler concatenates two adjacent literal strings to make a single string.

There-fore, after concatenation is performed on the two adjacent strings, 

the statement becomes the following:

printf ( ”count = %i\n”, count);


The ##Operator

The ##operator is used in macro definitions to join two tokens. It is preceded (or fol-lowed) 

by the name of a parameter to the macro.The preprocessor takes the actual argu-ment to 

the macro that is supplied when the macro is invoked and creates a single token out of 

that argument and whatever token follows (or precedes) the  ##.

Suppose, for example, that you have a list of variables x1through  x100.You can write a

macro called printx that simply takes as its argument an integer value  1–100 and displays

the corresponding  x variable, as shown here:

#define printx(n)  printf (”%i\n”, x ## n)

The portion of the define that reads

x ## n

says to use the tokens that occur before and after the  ##(the letter x and the argument n,

respectively) and make a single token out of them. So the call

printx (20);

is expanded into the following:

printf ( ”%i\n”, x20);

The printx macro can even use the previously defined printint macro to get the

variable name as well as its value displayed:

#define printx(n)  printint(x ## n)

The invocation

printx (10);

first expands into

printint (x10);

and then into

printf ( ”x10 ”“ = %i\n ”, x10);

and finally into the following:

printf ( ”x10 = %i\n”, x10);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值