koorkevani
koorkevani

Reputation: 321

Is the non-directive a legal c preprocesing directive?

The c99 standard says almost nothing about the non-directive - only that it's "a directive", in the sense of being illegal to place in a macro argument list (footnote 150, attached to 6.10.3p11).

One would assume this lack of definition means that any non-directive causes undefined behavior, and should be reported as an error, and this is mostly the case with both gcc and clang.

However, in both compilers, the line:

# 123 "filename"

is equivalent to:

# line 123 "filename"

even when the -std=c99 flag is set.

Why is that the case? I've only found a single mention of it online, without a resolution.

Upvotes: 2

Views: 179

Answers (2)

klutt
klutt

Reputation: 31379

Using -std=c99 does not automatically reject anything not specified with the C99 standard. If you want that, also add -pedantic. That generates a warning for the line.

k.c:1:3: warning: style of line directive is a GCC extension
    1 | # 123 "filename"
      |   ^~~

https://linux.die.net/man/1/gcc

-pedantic

Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, follows the version of the ISO C standard specified by any -std option used.

However, do note this:

Some users try to use -pedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.

A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -pedantic. We don't have plans to support such a feature in the near future.

Upvotes: 2

Eric Postpischil
Eric Postpischil

Reputation: 222714

C 2018 6.10 9 says:

The execution of a non-directive preprocessing directive results in undefined behavior.

So, yes, it is “legal” (the C standard does not prohibit you from including it in your program or prohibit a C implementation from defining the behavior), but its behavior is not defined by the C standard.

This paragraph is not present in the C 1999 standard, but then the behavior is still undefined by omission (C 1999 4 2: “… Undefined behavior is otherwise indicated in this International Standard by the words “undefined behavior” or by the omission of any explicit definition of behavior…”).

Upvotes: 4

Related Questions