Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Digraphs should not be used (MISRA C++ 2-5-1)

According to MISRA C++ 2-5-1 we should generally avoid messing up with digraphs. Though, I don't understand why we should also avoid the use of readable words and, or, not etc. to define common operators &&, ||, ...

The issue is even highlighted as "major" issue for Sonar/MISRA:

[Major]     Open    Replace this digraph 'and' by its equivalent '&&'
[Major]     Open    Replace this digraph 'and' by its equivalent '&&'
[Major]     Open    Replace this digraph 'or' by its equivalent '||'    
[Major]     Open    Replace this digraph 'or' by its equivalent '||'    
[Major]     Open    Replace this digraph 'or' by its equivalent '||'

Is the rule also including the human readable digraphs (that are quite different from the cryptic ??=, ??/) for a particular reason or the rule is just too generic? I haven't found any particular risk or side effect at using them, am I wrong?

Summing up

is there a functional reason for this MISRA rule to include also the human readable digraphs? Should I avoid them only to satisfy blindly a code compliance rule or there's some real tricky reason hiding behind?

like image 511
Alex Gidan Avatar asked Jun 17 '14 15:06

Alex Gidan


1 Answers

Digraphs and Trigraphs are only lexical sugar. The compiler will replace them with other single characters.

MISRA C++ rule 2-3-1 says "Trigraphs shall not be used."

Trigraphs are all characters which start with "??" and a third character which defines, what the trigraph means. (e.g. "??-" is the same as "~")

MISRA C++ 2008 does not enumerate these. So I assume, that all trigraphs are meant. These are:

??= ??/ ??’ ??( ??) ??! ??< ??> ??-

MISRA C++ rule 2-5-1 says "Digraphs shall not be used."

The Digraphs are e.g. "<%" or "%>" (is equal to "{" and "}").

MISRA C++ 2008 enumerates the forbidden ones:

<% %> <: :> %: %:%:

Digraphs and Trigraphs

For me they are relicts from a ancient time. You can write a C++ program e.g. without using any braces. They make source code unreadable:

void a()
<%
    int b<:2:> = <%0, 0%>;
%>

As far as I see, there is no rule in MISRA C++ 2008, that forbids the use of human readable logical operators (although they are very uncommon). This means the Sonar rule is more restrictive than MISRA C++ 2008. I think it is a bug.

In my opinion the C/C++ community isn't familiar with human readable logical operators. So they should be consequently avoided.

BTW: The C++ standard calls them trigraphs and "alternative tokens". The logical opterator alternatives are enumerated there as such.

like image 144
Stefan Weiser Avatar answered Nov 14 '22 17:11

Stefan Weiser