Search code examples
cconstantslanguage-lawyerundefined-behaviorextern

Is this aditional const on extern an UB?


I have the following:

//h.h file
#pragma once
struct A { int x; };

//a.c file
#include "h.h"
struct A* a;

//b.c
#include "h.h"
extern struct A* const a;
int main() {}

I added an extra const on extern declaration. Adding this const would be UB?

If It's not UB, doing like below inside main would be UB?

(*(struct A**)&a) = malloc(sizeof(struct A));

Solution

  • Yes. From Annex J.2:

    • Two declarations of the same object or function specify types that are not compatible (6.2.7).

    And 6.2.7 ¶2:

    All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

    And 6.7.3 ¶10:

    For two qualified types to be compatible, both shall have the identically qualified version of a compatible type; the order of type qualifiers within a list of specifiers or qualifiers does not affect the specified type.