通过添加一些特殊字符使 /* 的含义用于取消引用和划分而不是用于注释

make the meaning of /* for dereference and dividing not for commenting by adding some special character

我有这样的代码:

int quotient = 100/*ptr; 

其中 ptr 是指向整数的指针。

但是它以/*作为注释。
我怎样才能使除以指针取消引用值的意义?我必须输入什么额外的特殊字符才能具有此含义?

改成这样:

int quotient = 100/(*ptr); 

int quotient = 100/ *ptr;

/* together 用于多行注释,几乎所有我现在知道的语言。

发生这种情况是因为语言试图重用标记。 (* 在这种情况下)

解决方案是在 /* 之间放置一个 space 以击败最大咀嚼。

int quotient = 100 / *ptr;

另一种方法是添加括号或使用另一个局部变量:

int quotient = 100/(*ptr);

C 和 C++ 使用 maximal munch rule 来解析标记。标记后的最长有效匹配字符串将是下一个标记。

因此在 int quotient = 100/*ptr; 中,/* 将是一个标记,而不是两个标记 /*。这是该规则的不良影响。

In some situations, "maximal munch" leads to undesirable or unintuitive outcomes. For instance, in the C programming language, the statement x=y/*z; (without any whitespace) will probably lead to a syntax error, since the /* character sequence initiates a (unintended) comment that is either unterminated or terminated by the end token */ of some later, unrelated actual comment (comments in C do not nest). What was actually meant in the statement was to assign to the variable x the result of dividing the value in y by the value obtained by dereferencing pointer z; this would be perfectly valid (though not very common) code. It can be stated by making use of whitespace, or using x=y/(*z);.

https://en.wikipedia.org/wiki/Maximal_munch#Drawbacks

要解决此问题,您只需添加一个 space、新行或另一个虚拟标记(如注释)来分隔 /*。您也可以像其他答案一样用方括号括起表达式

int quotient = 100/ /* this will work */ *ptr;
int quotient = 100/
    *ptr; // this will also work

类似问题:Why doesn't a+++++b work in C?

首先,您可以将 *ptr 替换为 ptr[0],因为两者具有相同的语义:

int quotient = 100/ptr[0];

并且由于数组索引是可交换的,您可以交换操作数:

int quotient = 100/0[ptr];

对于普通人 reader,这可能看起来像是被零除,但当然 []/ 具有更高的优先级。 你可能想在那里放一个 space,以防万一:

int quotient = 100/0 [ptr];

恭喜,您现在有了一份终生工作!