ITman
ITman

Reputation: 141

Occurrences of question mark in C code

I am doing a simple program that should count the occurrences of ternary operator ?: in C source code. And I am trying to simplify that as much as it is possible. So I've filtered from source code these things:

  1. String literals " "
  2. Character constants ' '
  3. Trigraph sequences ??=, ??(, etc.
  4. Comments
  5. Macros

And now I am only counting the occurances of questionmarks.

So my question question is: Is there any other symbol, operator or anything else what could cause problem - contain '?' ?

Let's suppose that the source is syntax valid.

Upvotes: 4

Views: 508

Answers (3)

orlp
orlp

Reputation: 117681

In K&R ANSI C the only places where a question mark can validly occur are:

  1. String literals " "
  2. Character constants ' '
  3. Comments

Now you might notice macros and trigraph sequences are missing from this list.

I didn't include trigraph sequences since they are a compiler extension and not "valid C". I don't mean you should remove the check from your program, I'm trying to say you already went further then what's needed for ANSI C.

I also didn't include macros because when you're talking about a character that can occur in macros you can mean two things:

  1. Macro names/identifiers
  2. Macro bodies

The ? character can not occur in macro identifiers (http://stackoverflow.com/questions/369495/what-are-the-valid-characters-for-macro-names), and I see macro bodies as regular C code so the first list (string literals, character constants and comments*) should cover them too.

* Can macros validly contain comments? Because if I use this:

#define somemacro 15 // this is a comment

then // this is a comment isn't part of the macro. But what if I would compiler this C file with -D somemacro="15 // this is a comment"?

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

Run your tool on preprocessed source code (you can get this by running e.g. gcc -E). This will have done all macro expansions (as well as #include substitution), and eliminated all trigraphs and comments, so your job will become much easier.

Upvotes: 3

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

I think you found all places where a question-mark is introduced and therefore eliminated all possible false-positives (for the ternary op). But maybe you eliminated too much: Maybe you want to count those "?:"'s that get introduced by macros; you dont count those. Is that what you intend? If that's so, you're done.

Upvotes: 4

Related Questions