#DEfine pay attention

zhaozj2021-02-16  68

Here we talk about some misunderstandings of #define, because the last piece has already talked its main role, this is mainly a common macro trap. First of all. A classic example as follows.

#define private public # include

Using namespace std;

Class C

{

Private:

INT I;

}

INT main () {C C1; C1.I = 1; COUT <

<

}

#define actually let Private are so fragile, but reveal the root of #define traps, it is just a code replacement mechanism, in addition to this, it is nothing.

Let's take a look at the topic to see what kind of error will the definition below?

#DEFINE F (X) ((x) -1)

If this is a function, there is no problem INT f (int x) {returnx x-1;}

But here is the world of Define, f (x) only see a terrible space makes it makes the program if it appears.

f (10)

This code will eventually become

(10) (10-1) (10) Such a strange thing, of course, this code cannot be compiled, or can be checked. It is not so lucky to escape again. Let us continue.

#define abs (x) x> 0? x: -x (reference self C language traps and defects)

What is the problem with this code? Maybe everyone also noticed, I have been using countless () to write #define, not because I like () this thing, but when I am making the following call.

Z = ABS (A-B) // 呜, what will this be?

the answer is:

A-B> 0? A-B: -A-B

This is obviously not what we want, because when A-B <0 will return a -A-B, we must solve this problem, we will use () to solve it.

#define abs (x)> 0? (x) :-( x)

Now this code can work normally. As long as we keep the #define is a mechanism for code replacement, don't have any extravagance, you will avoid the above problems. In addition, because the macro is not a type, there is no data security check, there will be obstacles when debugging, so C has always advocated the use of const and inline to replace #define, maybe, # define really will disappear on the historical stage. But Define has not been forgotten in the C language era.

From http://community.9cbs.net/expert/topic/3195/3195102.xml?temp=.3936731

转载请注明原文地址:https://www.9cbs.com/read-13976.html

New Post(0)