Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is exactly an "invalid conversion specification"?

As per C11, chapter §7.21.6.1, P9

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Till time, my understanding was, for

  char str [] = "Sourav";
  • A statement like printf("%S", str); belong to the first sentence, there exist no CS as %S (UPPERCASE)
  • A statement like printf("%d", str); belongs to the second sentence (mismatch between CS and argument type, but the %d is not an "invalid" CS, anyway)

until advised otherwise by a recent comment thread.

Is my understanding wrong? Can the second statement also be categorized as "invalid" (PS- not "wrong") conversion specifier?


Update: The answer and the comment thread is deleted, here's a snap for <10K users.

like image 305
Sourav Ghosh Avatar asked Dec 19 '22 05:12

Sourav Ghosh


1 Answers

The "validity" of a conversion specification is determined by the standard paragraphs above the one you quoted:

7.21.6.1 - p4 to p8

Each conversion specification is introduced by the character %. After the %, the following appear in sequence: ...

The flag characters and their meanings are: ...

The conversion specifiers and their meanings are: ...

This here means that any conversion specification that is composed from the elements in the above lists is valid, all others are not in the eyes of the standard. That's why the paragraph in your code mentions two causes of UB. One is a specification that is not according to the grammar, and the other is specification and type mismatch.

The comment you linked to seems to use "invalid" colloquially. I.e. both uses of the conversion specifications are "invalid", since they lead to UB. But only the first is "invalid" from a language lawyer standpoint.

like image 135
StoryTeller - Unslander Monica Avatar answered Dec 28 '22 07:12

StoryTeller - Unslander Monica