一个关于 C++ 中类型强制的简单问题

发布于 2024-09-02 12:24:32 字数 298 浏览 4 评论 0原文

给定一个函数原型和一个类型定义:

int my_function(unsigned short x);
typedef unsigned short blatherskite;

以下情况是否由标准定义:

int main(int argc, char** argv) {
  int result;
  blatherskite b;

  b=3;
  result = my_function(b);
}

我是否可以通过函数原型获得类型强制?

Given a function prototype, and a type definition:

int my_function(unsigned short x);
typedef unsigned short blatherskite;

Is the following situation defined by standard:

int main(int argc, char** argv) {
  int result;
  blatherskite b;

  b=3;
  result = my_function(b);
}

Do I get type coercion predictably via the function prototype?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

固执像三岁 2024-09-09 12:24:32

如果您的问题实际上是关于参数和参数的类型是否匹配,那么答案是肯定的。 typedef 不会引入新类型,它只是为现有类型创建别名。变量 b 的类型为 unsigned int,就像参数一样,尽管 b 是使用 typedef-name blatherskite 声明的。

不过,你的例子并不能很好地证明这一点。所有整数类型在 C++ 中都可以相互转换,因此(忽略范围问题)即使 blatherskite 指定了不同的类型(新类型),代码也会具有已定义的行为。但事实并非如此。所以这也是完全有效的

void foo(unsigned int* p);
...
blatherskite *pb = 0;
foo(pb); // <- still valid

If your question is really about whether the types of the argument and the parameter match, then the answer is yes. typedef does not introduce a new type, it only creates alias for an existing one. Variable b has type unsigned int, just like the parameter, even though b is declared using typedef-name blatherskite.

Your example is not very good for demonstrating that though. All integral types are convertible to each other in C++, so (ignoring range issues) the code would have defined behavior even if blatherskite designated a different type (a new type). But it doesn't. So this is also perfectly valid

void foo(unsigned int* p);
...
blatherskite *pb = 0;
foo(pb); // <- still valid
心病无药医 2024-09-09 12:24:32

不需要类型强制。 typedef 只是同一类型的别名,因此您将一个 unsignedshort 传递给一个采用 unsignedshort 的函数。

No type coercion is needed. The typedef is just an alias for the same type, so you're passing an unsigned short to a function that takes an unsigned short.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文