简体   繁体   中英

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?

The call to func1(&g) is invalid. It is a constraint violation in C language, ie 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.

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 con vention 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 (ie might consider the constraint violation an "error"), but, again, the standard does not provide any guidance there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM