mrn
mrn

Reputation: 1081

Can a function call discard cons qualifier of its parameter?

The following code causes an error in Green Hills C compiler (error: type int * is incompatible with argument type const int*), while it only produces a warning and compiles with gcc (warning: passing argument 1 of ‘func’ discards ‘const’ qualifier from pointer target type).

void func1(int* a)
{
  (*a)++;
}

const int g = 100;

void func2(void)
{
  func1(&g);
}

Which behavior is according to C standard?

Upvotes: 0

Views: 99

Answers (2)

John Bollinger
John Bollinger

Reputation: 180968

Which behavior is according to C standard?

Both compiler behaviors conform with the standard. As @AnT already explained, the call func1(&g) violates a language constraint. The standard's requirement on the compiler in such a case is expressed by paragraph 5.1.1.3/1:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint [...]

As you can see, @Olaf is right that the standard does not distinguish different categories of diagnostics. That's an invention and convention of implementations, which generally distinguish between the two based on whether the situation is fatal to the compilation process. The standard has nothing further to say about what a compiler should do so when a constraint violation is detected, however, neither in general nor in this particular case, so it does not even indirectly dictate whether a "warning" or "error" should be emitted.

If the compiler does continue and eventually produces an executable, then the whole resulting program exhibits undefined behavior if at any point in its run it evaluates the problematic function call. This is a reason why a compiler might choose not to emit such a binary (i.e. might consider the constraint violation an "error"), but, again, the standard does not provide any guidance there.

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320631

The call to func1(&g) is invalid. It is a constraint violation in C language, i.e. it is what in everyday terminology is usually referred to as an "error". C language does not support implicit conversion of const int * value to int * type.

The fact that it is "just a warning" in GCC does not mean anything. Use -pedantic-errors switch in GCC to make it report constraint violations as "errors". Green Hills C compiler, as you observed yourself, reports it as an "error" without any help from your side.

Upvotes: 4

Related Questions