主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Rule 11.1

Conversions shall not be performed between a pointer to a function and any other type

自 R2024a 起

描述

规则定义

Conversions shall not be performed between a pointer to a function and any other type 1 .

理由

该规则禁止以下两种转换:

  • 从函数指针到其他任何类型的转换。这种转换会导致未定义行为。

  • 从一个函数指针到另一个函数指针的转换(如果函数指针具有不同的参量类型和返回类型)。

    这种转换会被禁止,因为通过类型不兼容的指针调用函数会导致未定义行为。

Polyspace 实现

Polyspace® 在检查此规则时,会同时考虑显式转换和隐式转换。但从 NULL(void*)0 进行的转换并不违反此规则。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

typedef void (*fp16) (short n);
typedef void (*fp32) (int n);

#include <stdlib.h>                     /* To obtain macro  NULL */

void func(void) {   /* Exception 1 - Can convert a null pointer 
                     * constant into a pointer to a function */
  fp16 fp1 = NULL;                 /* Compliant - exception  */
  fp16 fp2 = (fp16) fp1;           /* Compliant */
  fp32 fp3 = (fp32) fp1;           /* Non-compliant */
  if (fp2 != NULL) {}              /* Compliant - exception  */
  fp16 fp4 = (fp16) 0x8000;        /* Non-compliant - integer to 
                                    * function pointer */}

在此示例中,当出现以下情况时便会违反规则:

  • 类型为 fp16 的指针 fp1 转换为类型 fp32。函数指针类型 fp16fp32 具有不同的参量类型。

  • 整数转换为 fp16 类型。

当函数指针 fp1fp2 转换为 NULL 时,不违反规则。

检查信息

组:指针类型转换
类别:必需
AGC 类别:必需

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.