f



C and MISRA, blues... (arithmetic shifts)

I'm currently rewriting some numerical code for MISRA compliance.

Signed shifts are not defined by the C-standard, and the code-checker 
complaints. Well - no big surprise here. I knew that and did it 
nevertheless. Now I have to rewrite.


But do you do if you need them anyway? I need *lots* of them, so in 
despair I've just created this monster of unreadable code:


int ArithmeticShiftRight (int value, unsigned int shift)
{
   if (shift)
   {
     /* Get unsigned version of value to work with */
     unsigned int x = (unsigned int) value;

     /* replicate the sign-bit of value into all bits of SignMask: */
     unsigned int SignMask = ((unsigned int) -(value < 0));

     /* assemble the arithmetic shift from two unsigned shifts. */
     x = (x>>shift)|(SignMask<<(32-shift));

     /* writeback result as signed integer */
     value = (int) x;
   }
   return value;
}


I just had the urge to share this huge wtf code with you. It's horrible. 
It's unreadable, and all it does is doing a stupid shift.

Has anyone here seen a C-compiler that does something different than 
arithmetic shifts on signed integers in the last 20 years? I've used a 
lot of compilers over the years, and they all shifted arithmetic.

   Nils
0
4/24/2008 9:34:41 PM
comp.arch.embedded 20047 articles. 1 followers. Post Follow

92 Replies
656 Views

Similar Articles

[PageSpeed] 24

On 2008-04-24, Nils <n.pipenbrinck@cubic.org> wrote:
> I'm currently rewriting some numerical code for MISRA compliance.
>
> Signed shifts are not defined by the C-standard, and the code-checker 
> complaints. Well - no big surprise here. I knew that and did it 
> nevertheless. Now I have to rewrite.
>
>
> But do you do if you need them anyway? I need *lots* of them, so in 
> despair I've just created this monster of unreadable code:
>
>
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
>    if (shift)
>    {
>      /* Get unsigned version of value to work with */
>      unsigned int x = (unsigned int) value;
>
>      /* replicate the sign-bit of value into all bits of SignMask: */
>      unsigned int SignMask = ((unsigned int) -(value < 0));
>
>      /* assemble the arithmetic shift from two unsigned shifts. */
>      x = (x>>shift)|(SignMask<<(32-shift));
>
>      /* writeback result as signed integer */
>      value = (int) x;
>    }
>    return value;
> }
>
>
> I just had the urge to share this huge wtf code with you. It's horrible. 
> It's unreadable, and all it does is doing a stupid shift.

Here's something different, but I don't know if it's less ugly.

  int ArithmeticShiftRight (int value, unsigned int shift)
  {
    switch (shift)
     {
     case 0: return value;   
     case 1: return value/2;
     case 2: return value/4;
     case 3: return value/8;
     ...
     }  
  }

[It only handles positive values for the shift parameter.]

One assumes the compiler is bright enough to optimize value/N to
an arithmetic right shift in the case where N is a constant
power of two.  Since the case values are contiguous and
0-based, that ought to turn into some sort of indexed or
table-driven jump that shouldn't result in more that a couple
instructions of overhead.

> Has anyone here seen a C-compiler that does something
> different than arithmetic shifts on signed integers in the
> last 20 years? I've used a lot of compilers over the years,
> and they all shifted arithmetic.

I've never seen one that doesn't do an arithmetic right shift
on signed value...

-- 
Grant Edwards                   grante             Yow! Hello?  Enema Bondage?
                                  at               I'm calling because I want
                               visi.com            to be happy, I guess ...
0
grante (5416)
4/24/2008 9:55:00 PM

Nils wrote:

> I'm currently rewriting some numerical code for MISRA compliance.
>
> Signed shifts are not defined by the C-standard, and the code-checker
> complaints. Well - no big surprise here. I knew that and did it
> nevertheless. Now I have to rewrite.
>
> But do you do if you need them anyway? I need *lots* of them, so in
> despair I've just created this monster of unreadable code:
>
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
>    if (shift)
>    {
>      /* Get unsigned version of value to work with */
>      unsigned int x = (unsigned int) value;
>
>      /* replicate the sign-bit of value into all bits of SignMask: */
>      unsigned int SignMask = ((unsigned int) -(value < 0));
>
>      /* assemble the arithmetic shift from two unsigned shifts. */
>      x = (x>>shift)|(SignMask<<(32-shift));
>
>      /* writeback result as signed integer */
>      value = (int) x;
>    }
>    return value;
> }
>
> I just had the urge to share this huge wtf code with you. It's horrible.
> It's unreadable, and all it does is doing a stupid shift.
>
> Has anyone here seen a C-compiler that does something different than
> arithmetic shifts on signed integers in the last 20 years? I've used a
> lot of compilers over the years, and they all shifted arithmetic.

I am sure you have looked into sign extend and possibly a divide
something like

   if (shift)  value  = value  / (1 << shift);

I haven't checked what misra says about signed divide by integer
but one possibility is the compiler may very well change the code
into an arithmetic shift. One possible implementation other than
a function call might be

#define asr(shift,value) if (shift)  (value  = value  / (1 << shift))

if shift is a constant and 0 then the compiler would eliminate the
statement with dead code removal.

w..

0
walter20 (887)
4/24/2008 10:05:50 PM
Grant Edwards schrieb:
> Here's something different, but I don't know if it's less ugly.
> 
>   int ArithmeticShiftRight (int value, unsigned int shift)
>   {
>     switch (shift)
>      {
>      case 0: return value;   
>      case 1: return value/2;
>      case 2: return value/4;
>      case 3: return value/8;
>      ...
>      }  
>   }
> 

I thought about this one as well. With loop-unswitching optimization 
enabled it wouldn't just give a bit of code-bloat but give perfect code.

However, it does not work if value is negative because  (-7/2) != 
(-7>>1). A little known fact and often we can live with it, but I can't.

To bad..


> One assumes the compiler is bright enough to optimize value/N to
> an arithmetic right shift in the case where N is a constant
> power of two.  Since the case values are contiguous and
> 0-based, that ought to turn into some sort of indexed or
> table-driven jump that shouldn't result in more that a couple
> instructions of overhead.

Speaking of optimizations: I just had a look at the assembly output and 
GCC generates pretty good code for my function. It does not turn it into 
a arithmetic shift. Guess that would be asking for to much, but it does 
some very clever tricks :-)

   Nils
0
4/24/2008 10:12:30 PM
Nils wrote:
> I'm currently rewriting some numerical code for MISRA compliance.
> 
> Signed shifts are not defined by the C-standard, and the code-checker 
> complaints. Well - no big surprise here. I knew that and did it 
> nevertheless. Now I have to rewrite.
> 
> 
> But do you do if you need them anyway? I need *lots* of them, so in 
> despair I've just created this monster of unreadable code:
> 

How about:

int ArithmeticShiftRight (int value, unsigned int shift)
{
    if (value < 0) {
	return -((int) (((unsigned int) (-value)) >> shift);
    } else {
	return ((int) (((unsigned int) (value)) >> shift);
    }
}

It's still horrible, but it probably compiles to better code.
0
david.brown (580)
4/24/2008 10:17:17 PM
"Nils" <n.pipenbrinck@cubic.org> wrote in message news:67ccn9F2na9h5U1@mid.uni-berlin.de...
> I'm currently rewriting some numerical code for MISRA compliance.
>
> Signed shifts are not defined by the C-standard, and the code-checker complaints. Well - no big surprise here. I knew 
> that and did it nevertheless. Now I have to rewrite.

Sounds like you're going to write some seriously unreadable, unmaintainable
and most likely buggy code... Try to explain that one to your manager!

The C standard rather stupidly accomodates the merely theoretical case
of one's complement (where the obvious implementation of signed shift
would round negative numbers differently). MISRA has some good rules
but there are a lot of bad ones as well. It's best to pick a subset - the last
time I looked at it I threw out more than half of the rules.

> Has anyone here seen a C-compiler that does something different than arithmetic shifts on signed integers in the last 
> 20 years? I've used a lot of compilers over the years, and they all shifted arithmetic.

There is no compiler that doesn't correctly implement signed arithmetic.
Nobody could get away with creating a compiler that can't compile existing
code.

Wilco 


0
4/24/2008 10:26:52 PM
"David Brown" <david.brown@hesbynett.removethisbit.no> wrote in message 
news:5_GdnfetN7l7m4zVnZ2dneKdnZydnZ2d@lyse.net...
> Nils wrote:
>> I'm currently rewriting some numerical code for MISRA compliance.
>>
>> Signed shifts are not defined by the C-standard, and the code-checker complaints. Well - no big surprise here. I knew 
>> that and did it nevertheless. Now I have to rewrite.
>>
>>
>> But do you do if you need them anyway? I need *lots* of them, so in despair I've just created this monster of 
>> unreadable code:
>>
>
> How about:
>
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
>    if (value < 0) {
> return -((int) (((unsigned int) (-value)) >> shift);
>    } else {
> return ((int) (((unsigned int) (value)) >> shift);
>    }
> }
>
> It's still horrible, but it probably compiles to better code.

But it's incorrect as it doesn't round the same way.

Wilco 


0
4/24/2008 10:28:02 PM
Nils wrote:

> But do you do if you need them anyway? 

Check very thoroughly why you think you need them.  Shifting is not 
really a numerical operation, so why should something you describe as 
"numerical code" need it in the first place?

> I just had the urge to share this huge wtf code with you. It's horrible. 
> It's unreadable, and all it does is doing a stupid shift.

Erm, how is it MISRA's fault if you decide to write such horrible code? 
  Why not express numerical operations by use of the arithmetic 
operators they're supposed to represent?

#define ASR(input, count) (input / (signed)(1 << count))
0
HBBroeker (925)
4/24/2008 10:29:31 PM
"Walter Banks" <walter@bytecraft.com> wrote in message news:4811043E.B3ACBFAE@bytecraft.com...

> I am sure you have looked into sign extend and possibly a divide
> something like
>
>   if (shift)  value  = value  / (1 << shift);

That doesn't round correctly either.

> #define asr(shift,value) if (shift)  (value  = value  / (1 << shift))

This has at least 4 different problems...

Wilco 


0
4/24/2008 10:33:39 PM

Wilco Dijkstra wrote:

> "Walter Banks" <walter@bytecraft.com> wrote in message news:4811043E.B3ACBFAE@bytecraft.com...
>
> > I am sure you have looked into sign extend and possibly a divide
> > something like
> >
> >   if (shift)  value  = value  / (1 << shift);
>
> That doesn't round correctly either.
>
> > #define asr(shift,value) if (shift)  (value  = value  / (1 << shift))
>
> This has at least 4 different problems...
>

I hit return too soon.
:)



0
walter20 (887)
4/24/2008 10:36:03 PM
Nils wrote:
> 
.... snip ...
> 
> int ArithmeticShiftRight (int value, unsigned int shift) {
>    if (shift) {
>      /* Get unsigned version of value to work with */
>      unsigned int x = (unsigned int) value;

This operation is not possible in a standard C system.  Think about
what would happen to negative values in sign-magnitude, 1's
complement, or 2's complement.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/24/2008 11:26:41 PM
On 2008-04-24, Nils <n.pipenbrinck@cubic.org> wrote:
> Grant Edwards schrieb:
>> Here's something different, but I don't know if it's less ugly.
>> 
>>   int ArithmeticShiftRight (int value, unsigned int shift)
>>   {
>>     switch (shift)
>>      {
>>      case 0: return value;   
>>      case 1: return value/2;
>>      case 2: return value/4;
>>      case 3: return value/8;
>>      ...
>>      }  
>>   }
>> 
>
> I thought about this one as well. With loop-unswitching
> optimization enabled it wouldn't just give a bit of code-bloat
> but give perfect code.
>
> However, it does not work if value is negative because (-7/2)
> != (-7>>1). A little known fact and often we can live with it,
> but I can't.

Doh. I forgot about that. I guess I write too much python:

  $ python
  Python 2.4.4 (#1, Mar 19 2008, 14:48:47) 
  [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
  Type "help", "copyright", "credits" or "license" for more
  information.
  >>> -7/2
  -4
  >>> -7>>1
  -4
  >>> 

-- 
Grant Edwards                   grante             Yow! Is this sexual
                                  at               intercourse yet??  Is it,
                               visi.com            huh, is it??
0
grante (5416)
4/25/2008 12:11:28 AM
David Brown wrote:
> Nils wrote:
>> I'm currently rewriting some numerical code for MISRA compliance.
>>
>> Signed shifts are not defined by the C-standard, and the code-checker 
>> complaints. Well - no big surprise here. I knew that and did it 
>> nevertheless. Now I have to rewrite.
>>
>>
>> But do you do if you need them anyway? I need *lots* of them, so in 
>> despair I've just created this monster of unreadable code:
>>
> 
> How about:
> 
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
>    if (value < 0) {
>     return -((int) (((unsigned int) (-value)) >> shift);
>    } else {
>     return ((int) (((unsigned int) (value)) >> shift);
>    }
> }
> 
> It's still horrible, but it probably compiles to better code.

Part of the problem is defining what you want.  C works for
two's complement, ones complement, and absolute value and sign.

If you define arithmetic right shift as "shift right leaving the sign bit 
unchanged", then you get the following:
Expression   2scomp  1scomp  AV&S
ASR(-4,1)    -2      -2      -2-UINT_MAX/2
ASR(-3,1)    -2      -1      -1-UINT_MAX/2
-4/2         -2      -2      -2
-3/2         -1      -1      -1

The last expression is only defined that way in C99.

Do you want to implement the two's complement version of ASR in all cases 
or the "shift right leaving the sign bit unchanged" or something else?

-- 
Thad
0
ThadSmith (1280)
4/25/2008 4:08:00 AM
In article <67ccn9F2na9h5U1@mid.uni-berlin.de>, Nils says...
> I'm currently rewriting some numerical code for MISRA compliance.
> 
> Signed shifts are not defined by the C-standard, and the code-checker 
> complaints. Well - no big surprise here. I knew that and did it 
> nevertheless. Now I have to rewrite.
> 
> 
> But do you do if you need them anyway? I need *lots* of them, so in 
> despair I've just created this monster of unreadable code:

Echoing the question.  What do you need them for that's not covered by a 
divide by a power of 2?  


What about

int asr( int x, unsigned int shift)
{
unsigned int temp;

temp=(unsigned int)x;

if( x < 0) {
     temp = ~((~temp) >> shift);
     }
else {
     temp >>= shift;
     }
return (int)temp;
}

Does that cover all the cases?  For a negative value it converts the 
sign extend to a zero extend and the positive case works as usual.

Commenting left to the user.

It's small enough you could probably make a macro (with some loss of 
clarity)  and for constant shifts a good compiler might end up 
optimizing it back to a ASR.  Maybe?

Or, take the simple way out and declare an exception (whatever the term 
is MISRA uses for a formal waiver of a rule).  As I recall they can 
apply at indivual case, project level or as company policy as an 
exception.  They do need to be documented though.

Robert
** Posted from http://www.teranews.com **
0
sub2 (468)
4/25/2008 4:33:31 AM
Wilco Dijkstra wrote:
> "David Brown" <david.brown@hesbynett.removethisbit.no> wrote in message 
> news:5_GdnfetN7l7m4zVnZ2dneKdnZydnZ2d@lyse.net...
>> Nils wrote:
>>> I'm currently rewriting some numerical code for MISRA compliance.
>>>
>>> Signed shifts are not defined by the C-standard, and the code-checker complaints. Well - no big surprise here. I knew 
>>> that and did it nevertheless. Now I have to rewrite.
>>>
>>>
>>> But do you do if you need them anyway? I need *lots* of them, so in despair I've just created this monster of 
>>> unreadable code:
>>>
>> How about:
>>
>> int ArithmeticShiftRight (int value, unsigned int shift)
>> {
>>    if (value < 0) {
>> return -((int) (((unsigned int) (-value)) >> shift);
>>    } else {
>> return ((int) (((unsigned int) (value)) >> shift);
>>    }
>> }
>>
>> It's still horrible, but it probably compiles to better code.
> 
> But it's incorrect as it doesn't round the same way.
> 
> Wilco 
> 
> 

Is the rounding of shifts like this well defined in C?  I can't remember 
the exact rules off-hand - perhaps that's why MISRA doesn't like right 
shifts of signed integers!

Would this be more correct?

	return ~((int) (((unsigned int) (~value)) >> shift);

I haven't checked it - in particular, corner cases must be checked.  I'm 
just spouting ideas for the OP.
0
david2384 (2168)
4/25/2008 7:40:35 AM
"David Brown" <david@westcontrol.removethisbit.com> wrote in message news:48118b7c$0$2677$8404b019@news.wineasy.se...
> Wilco Dijkstra wrote:
>> "David Brown" <david.brown@hesbynett.removethisbit.no> wrote in message 
>> news:5_GdnfetN7l7m4zVnZ2dneKdnZydnZ2d@lyse.net...
>>> Nils wrote:
>>>> I'm currently rewriting some numerical code for MISRA compliance.
>>>>
>>>> Signed shifts are not defined by the C-standard, and the code-checker complaints. Well - no big surprise here. I 
>>>> knew that and did it nevertheless. Now I have to rewrite.
>>>>
>>>>
>>>> But do you do if you need them anyway? I need *lots* of them, so in despair I've just created this monster of 
>>>> unreadable code:
>>>>
>>> How about:
>>>
>>> int ArithmeticShiftRight (int value, unsigned int shift)
>>> {
>>>    if (value < 0) {
>>> return -((int) (((unsigned int) (-value)) >> shift);
>>>    } else {
>>> return ((int) (((unsigned int) (value)) >> shift);
>>>    }
>>> }
>>>
>>> It's still horrible, but it probably compiles to better code.
>>
>> But it's incorrect as it doesn't round the same way.
>>
>> Wilco
>
> Is the rounding of shifts like this well defined in C?  I can't remember the exact rules off-hand - perhaps that's why 
> MISRA doesn't like right shifts of signed integers!

No it's not well defined, just like most other things in C, but who cares anyway?!?

Compiler writers agree on most of these things, so in reality these things are
extremely well defined. Basically nobody cares about what the C standard says
exactly as long as their code compiles. If it doesn't work on a particular compiler,
it is that compiler's fault. I know, I have dealt with angry customers with millions of
lines of code that didn't compile on our expensive but strict ANSI C compiler...

> Would this be more correct?
>
> return ~((int) (((unsigned int) (~value)) >> shift);
>
> I haven't checked it - in particular, corner cases must be checked.  I'm just spouting ideas for the OP.

That's right indeed (replacing the first return above). Of course this still gives you
correct behaviour only on 2-complement's CPUs. So it adds a lot of overhead
and bugs (given only the OP got it right first time) for no gain whatsoever...

Wilco 


0
4/25/2008 11:10:51 AM
"Nils" <n.pipenbrinck@cubic.org> wrote in message 
news:67ccn9F2na9h5U1@mid.uni-berlin.de...
> I'm currently rewriting some numerical code for MISRA compliance.
>
> Signed shifts are not defined by the C-standard, and the code-checker 
> complaints. Well - no big surprise here. I knew that and did it 
> nevertheless. Now I have to rewrite.
>
>
> But do you do if you need them anyway? I need *lots* of them, so in 
> despair I've just created this monster of unreadable code:
>
>
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
>   if (shift)
>   {
>     /* Get unsigned version of value to work with */
>     unsigned int x = (unsigned int) value;
>
>     /* replicate the sign-bit of value into all bits of SignMask: */
>     unsigned int SignMask = ((unsigned int) -(value < 0));
>
>     /* assemble the arithmetic shift from two unsigned shifts. */
>     x = (x>>shift)|(SignMask<<(32-shift));
>
>     /* writeback result as signed integer */
>     value = (int) x;
>   }
>   return value;
> }
>

IMHO the point is being missed here.   MISRA is intended to assist in making 
your code safer.  Obfuscation is never safer - from any point of view 
(review, error #, maintenance, etc.).    MISRA is a "guide", so let it be 
just that.  Rigorous compliance at all cost in an embedded system will 
result in junk code.

Our approach to this would be to run a check on the code, and let all the 
none compliances be documented.  Most of these non compliances can then be 
cleared up with the minimum of effort, but there will be some for which it 
makes no sense to change the code.  Therefore only a handful of 
non-compliances make it through to the code review phase.  During the code 
review actions will be raised to - for example - check exactly what the 
compiler does given the input.  The result of this check (test) is then also 
documented.  Once this is done the senior developer can deviate the 
remaining non-compliances with a sound rational argument, safe in the 
knowledge that (in combination with other testing) the code is going to 
behave as intended.  MISRA has done its job - it has highlighted a possible 
flaw in your code.  The engineers have done their job to ensure that the 
highlighted items are removed or guaranteed to do what is expected.

Which is safer - to have a single line that shifts code in an easily 
understandable, obvious way, that is reviewed, tested and checked, or to 
replace this with what by your own admission is more confusing.

-- 
Regards,
Richard.

+ http://www.FreeRTOS.org & http://www.FreeRTOS.org/shop
17 official architecture ports, more than 5000 downloads per month.

+ http://www.SafeRTOS.com
Certified by T�V as meeting the requirements for safety related systems.


0
noemail2969 (253)
4/25/2008 11:36:20 AM
Wilco Dijkstra wrote:
> "David Brown" <david@westcontrol.removethisbit.com> wrote:
>
.... snip ...
>
>> Is the rounding of shifts like this well defined in C?  I can't
>> remember the exact rules off-hand - perhaps that's why MISRA
>> doesn't like right shifts of signed integers!
> 
> No it's not well defined, just like most other things in C, but
> who cares anyway?!?
> 
> Compiler writers agree on most of these things, so in reality
> these things are extremely well defined. Basically nobody cares
> about what the C standard says exactly as long as their code
> compiles. If it doesn't work on a particular compiler, it is
> that compiler's fault. I know, I have dealt with angry customers
> with millions of lines of code that didn't compile on our
> expensive but strict ANSI C compiler...

You need copies of the C standard to hand out.  Most of those
problems have been discussed here, so you have a good selection of
immediate answers and suggestions available.

> 
>> Would this be more correct?
>>
>> return ~((int) (((unsigned int) (~value)) >> shift);
>>
>> I haven't checked it - in particular, corner cases must be
>> checked.  I'm just spouting ideas for the OP.
> 
> That's right indeed (replacing the first return above). Of course
> this still gives you correct behaviour only on 2-complement's
> CPUs. So it adds a lot of overhead and bugs (given only the OP
> got it right first time) for no gain whatsoever...

It's still fundamentally wrong - you can't guarantee unsigned to
signed casts, because an overflow may occur, and the result is
implementation defined behaviour.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/25/2008 12:51:08 PM
FreeRTOS.org wrote:
> "Nils" <n.pipenbrinck@cubic.org> wrote in message
> news:67ccn9F2na9h5U1@mid.uni-berlin.de...
>> I'm currently rewriting some numerical code for MISRA compliance.
>>
>> Signed shifts are not defined by the C-standard, and the code-checker
>> complaints. Well - no big surprise here. I knew that and did it
>> nevertheless. Now I have to rewrite.
>>
>>
>> But do you do if you need them anyway? I need *lots* of them, so in
>> despair I've just created this monster of unreadable code:
>>
>>
>> int ArithmeticShiftRight (int value, unsigned int shift)
>> {
>>   if (shift)
>>   {
>>     /* Get unsigned version of value to work with */
>>     unsigned int x = (unsigned int) value;
>>
>>     /* replicate the sign-bit of value into all bits of SignMask: */
>>     unsigned int SignMask = ((unsigned int) -(value < 0));
>>
>>     /* assemble the arithmetic shift from two unsigned shifts. */
>>     x = (x>>shift)|(SignMask<<(32-shift));
>>
>>     /* writeback result as signed integer */
>>     value = (int) x;
>>   }
>>   return value;
>> }
>>
>
> IMHO the point is being missed here.   MISRA is intended to assist in
> making your code safer.  Obfuscation is never safer - from any point
> of view (review, error #, maintenance, etc.).    MISRA is a "guide",
> so let it be just that.  Rigorous compliance at all cost in an
> embedded system will result in junk code.
>
> Our approach to this would be to run a check on the code, and let all
> the none compliances be documented.  Most of these non compliances
> can then be cleared up with the minimum of effort, but there will be
> some for which it makes no sense to change the code.  Therefore only
> a handful of non-compliances make it through to the code review
> phase.  During the code review actions will be raised to - for
> example - check exactly what the compiler does given the input.  The
> result of this check (test) is then also documented.  Once this is
> done the senior developer can deviate the remaining non-compliances
> with a sound rational argument, safe in the knowledge that (in
> combination with other testing) the code is going to behave as
> intended.  MISRA has done its job - it has highlighted a possible
> flaw in your code.  The engineers have done their job to ensure that
> the highlighted items are removed or guaranteed to do what is
> expected.
> Which is safer - to have a single line that shifts code in an easily
> understandable, obvious way, that is reviewed, tested and checked, or
> to replace this with what by your own admission is more confusing.

This is IMO exactly how MISRA should be used.
I've been obeying MISRA in my coding at work for years (well, sort of), 
while there are some things I think are very good (e.g. it makes you think 
very carefully about casting and potential overflows, it doesn't like magic 
numbers, etc etc), there are some things I get annoyed at, such as:

* You're not supposed to use "goto".  Avoiding this when you're learning to 
write code is good practise, but it's very useful in a limited set of 
circumstances, if used properly.  I remember a manager of mine telling a 
work colleague once that using "goto" was bad practise, I then showed my 
colleague my copy of K+R which basically put him right.

* You're not supposed to exit from a controlled loop prematurely.

* ...  Hmm, actually I could go on for a while.  Suffice to say, there are a 
few things...!

I've seen some tidy well-written code turned inside out and made 
semi-unreadable by trying to make it MISRA compliant.  If it makes code more 
complicated (and more error-prone) then it's doing the opposite of what's 
intended.  I had a chat with a manager of mine about this once and he said 
that MISRA was basically a guide, obey it if you can, but if there is a 
problem with doing this then all that was needed was to document the 
non-compliances.  For me, this is a far more sensible approach.  Sort out 
the obvious clangers, but don't turn good neat code into jumbled unreadable 
rubbish just to satisfy MISRA!!

The problem is there is some misunderstanding here.  MISRA lists it's rules 
as "recommended" and "required" (or something like that), which makes it 
sound like "required" rules MUST be obeyed, which doesn't appear to be the 
case from what I now understand.

R. 


0
raphillips (57)
4/25/2008 12:52:32 PM
Hans-Bernhard Br�ker wrote:
> Nils wrote:
> 
>> But do you do if you need them anyway?
> 
> Check very thoroughly why you think you need them.  Shifting is
> not really a numerical operation, so why should something you
> describe as "numerical code" need it in the first place?

Shifting IS a numerical operation.  Read the following description,
from the C standard.  Notice the 'undefined' cases for negative
operands.

  6.5.7  Bitwise shift operators

  Syntax
  [#1]
          shift-expr:
                  additive-expr
                  shift-expr << additive-expr
                  shift-expr >> additive-expr

  Constraints

  [#2] Each of the operands shall have integer type.

  Semantics

  [#3] The integer promotions are performed  on  each  of  the
  operands.   The  type  of the result is that of the promoted
  left operand.  If the value of the right operand is negative
  or  is  greater  than  or equal to the width of the promoted
  left operand, the behavior is undefined.

  [#4] The result of E1  <<  E2  is  E1  left-shifted  E2  bit
  positions; vacated bits are filled with zeros.  If E1 has an
  unsigned type, the value of the result  is  E1+2E2,  reduced
  modulo  one more than the maximum value representable in the
  result type.  If E1 has a signed type and nonnegative value,
  and E1+2E2 is representable in the result type, then that is
  the resulting value; otherwise, the behavior is undefined.

  [#5] The result of E1 >>  E2  is  E1  right-shifted  E2  bit
  positions.  If E1 has an unsigned type or if E1 has a signed
  type and a nonnegative value, the value of the result is the
  integral part of the quotient of E1 divided by the quantity,
  2 raised to the power E2.  If E1 has a  signed  type  and  a
  negative  value,  the  resulting  value  is  implementation-
  defined.


-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/25/2008 1:38:03 PM
In message <%_iQj.112101$5i5.67274@newsfe6-gui.ntli.net>, Wilco Dijkstra 
<Wilco_dot_Dijkstra@ntlworld.com> writes
>> Is the rounding of shifts like this well defined in C?  I can't 
>>remember the exact rules off-hand - perhaps that's why
>> MISRA doesn't like right shifts of signed integers!
>
>No it's not well defined, just like most other things in C, but who 
>cares anyway?!?
>
>Compiler writers agree on most of these things, so in reality these things are
>extremely well defined. Basically nobody cares about what the C standard says

This is true in practice.

>exactly as long as their code compiles.

Yes.  Actually as long as the behaviour of the compiler is known 
documented and repeatable the standard does not matter in reality.  Most 
embedded compilers are not ISO-C99 compliant but mostly ISO-C90/95 with 
compiler and target extensions.

>If it doesn't work on a particular compiler,
>it is that compiler's fault. I know, I have dealt with angry customers 
>with millions of
>lines of code that didn't compile on our expensive but strict ANSI C 
>compiler...

I assume you mean ISO-C compiler. Which standard? C90, C95, C99?

I do have an email  where a user says:

"We have moved from abc compiler to XYZ compiler. We used to compile 
with abc and get no errors. We now using xyz compiler we get lots of 
errors. We think this is because your xyz compiler is more strict than 
the abc compiler.

Please can you supply us a version of the xyz compiler with a less 
strict parser."

Yes I do have all the names.



-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/25/2008 2:21:13 PM
In article <67ccn9F2na9h5U1@mid.uni-berlin.de>, Nils says...
> I'm currently rewriting some numerical code for MISRA compliance.
> 
> Signed shifts are not defined by the C-standard, and the code-checker 
> complaints. Well - no big surprise here. I knew that and did it 
> nevertheless. Now I have to rewrite.
> 
> 
> But do you do if you need them anyway? I need *lots* of them, so in 
> despair I've just created this monster of unreadable code:

Echoing the question.  What do you need them for that's not covered by a 
divide by a power of 2?  


What about

int asr( int x, unsigned int shift)
{
unsigned int temp;

temp=(unsigned int)x;

if( x < 0) {
     temp = ~((~temp) >> shift);
     }
else {
     temp >>= shift;
     }
return (int)temp;
}

Does that cover all the cases?  For a negative value it converts the 
sign extend to a zero extend and the positive case works as usual.

Commenting left to the user.

It's small enough you could probably make a macro (with some loss of 
clarity)  and for constant shifts a good compiler might end up 
optimizing it back to a ASR.  Maybe?

Or, take the simple way out and declare an exception (whatever the term 
is MISRA uses for a formal waiver of a rule).  As I recall they can 
apply at indivual case, project level or as company policy as an 
exception.  They do need to be documented though.

Robert
** Posted from http://www.teranews.com **
0
sub2 (468)
4/25/2008 2:28:50 PM
In message <UmjQj.14994$yD2.11517@text.news.virginmedia.com>, 
FreeRTOS.org <noemail@given.com> writes
>
>IMHO the point is being missed here.   MISRA is intended to assist in making
>your code safer.  Obfuscation is never safer - from any point of view
>(review, error #, maintenance, etc.).    MISRA is a "guide", so let it be
>just that.  Rigorous compliance at all cost in an embedded system will
>result in junk code.

*Personally* I would not disagree with that.  Strict blind adherence to 
any set of (arbitrary) rules should avoided.   There is AFAIK in MISRA-C 
room for deviations. If you can document a reason (that will stand up in 
court in 3 years time) for doing something different then do that.

* All comments here are purely personal and not representing any 
company, organisation or body other than mine.

>Our approach to this would be to run a check on the code, and let all the
>none compliances be documented.  Most of these non compliances can then be
>cleared up with the minimum of effort, but there will be some for which it
>makes no sense to change the code.

Sounds very sensible to me.

> Therefore only a handful of
>non-compliances make it through to the code review phase.  During the code
>review actions will be raised to - for example - check exactly what the
>compiler does given the input.  The result of this check (test) is then also
>documented.

You do need to know exactly what your compiler will do. It is amazing 
how many people make blind assumptions about C compilers.

>Once this is done the senior developer can deviate the
>remaining non-compliances with a sound rational argument, safe in the
>knowledge that (in combination with other testing) the code is going to
>behave as intended.

Sounds good to me. You have documented the behaviour of the tools and 
reasons for doing "unsafe" things because in this particular instance it 
is the best solution and is not "unsafe" bea.

> MISRA has done its job - it has highlighted a possible
>flaw in your code.  The engineers have done their job to ensure that the
>highlighted items are removed or guaranteed to do what is expected.

Precisely...... The point is that behaviour is EXACTLY as expected and 
fully documented. Ie reliable, repeatable and safe as reasonably 
practicable.

>Which is safer - to have a single line that shifts code in an easily
>understandable, obvious way, that is reviewed, tested and checked, or to
>replace this with what by your own admission is more confusing.

Rule is rules guv... more than my jobs worff to....

:-)


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/25/2008 2:57:05 PM
Richard Phillips wrote:
> 
.... snip ...
> 
> The problem is there is some misunderstanding here.  MISRA lists
> it's rules as "recommended" and "required" (or something like
> that), which makes it sound like "required" rules MUST be obeyed,
> which doesn't appear to be the case from what I now understand.

The only 'required' rules are those of the C standard.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/25/2008 3:06:19 PM
In message <kukQj.59491$h65.48326@newsfe2-gui.ntli.net>, Richard 
Phillips <raphillips@ntlworld.com> writes
>
>This is IMO exactly how MISRA should be used.
>I've been obeying MISRA in my coding at work for years (well, sort of),
>while there are some things I think are very good (e.g. it makes you think
>very carefully about casting and potential overflows, it doesn't like magic
>numbers, etc etc), there are some things I get annoyed at, such as:
>
>* You're not supposed to use "goto".  Avoiding this when you're learning to
>write code is good practise, but it's very useful in a limited set of
>circumstances, if used properly.

This is true.

>I remember a manager of mine telling a
>work colleague once that using "goto" was bad practise, I then showed my
>colleague my copy of K+R which basically put him right.


Maybe. IT was AFAIK Dykstra who said goto was bad and no one has 
challenged that with a convincing strategy for using goto. Mainly 
because the majority who do use it tend to miss use it.  So it should 
not normally be used but...

>* You're not supposed to exit from a controlled loop prematurely.
>
>* ...  Hmm, actually I could go on for a while.  Suffice to say, there are a
>few things...!

All of the MISRA rules are good *some* of the time. Where they are not 
it is up to you to come up with a project specific reason why not.

>I've seen some tidy well-written code turned inside out and made
>semi-unreadable by trying to make it MISRA compliant.

I know what you mean it is the "tick the box" brigade who want to say we 
are MISRA compliant without actually using any Engineering thought on 
it.

>  If it makes code more
>complicated (and more error-prone) then it's doing the opposite of what's
>intended.

Hence MIStRAy-C A spoof on MISRA-C

http://www.phaedsys.demon.co.uk/chris/mistrayc/

> I had a chat with a manager of mine about this once and he said
>that MISRA was basically a guide, obey it if you can, but if there is a
>problem with doing this then all that was needed was to document the
>non-compliances.  For me, this is a far more sensible approach.

I personally believe this is the way it is meant to be used.

> Sort out
>the obvious clangers, but don't turn good neat code into jumbled unreadable
>rubbish just to satisfy MISRA!!

Any suggestions on how the MISRA team can stop people doing this All 
methods must be legal under the UN human rights and Geneva conventions. 
Water-boarding or stringing up by their thumbs for  recalcitrant 
programmers and managers  may be deserved and satisfying but we can't 
writ it in to a coding standard :-)

>The problem is there is some misunderstanding here.  MISRA lists it's rules
>as "recommended" and "required" (or something like that), which makes it
>sound like "required" rules MUST be obeyed, which doesn't appear to be the
>case from what I now understand.

It was required and advisory. IE those that should normally be used and 
those which are useful a lot of the time.

Any suggestions for a different nomenclature?

-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/25/2008 3:34:35 PM
"Chris H" <chris@phaedsys.org> wrote in message news:punstsIZjeEIFAMn@phaedsys.demon.co.uk...
> In message <%_iQj.112101$5i5.67274@newsfe6-gui.ntli.net>, Wilco Dijkstra <Wilco_dot_Dijkstra@ntlworld.com> writes
>>> Is the rounding of shifts like this well defined in C?  I can't remember the exact rules off-hand - perhaps that's 
>>> why
>>> MISRA doesn't like right shifts of signed integers!
>>
>>No it's not well defined, just like most other things in C, but who cares anyway?!?
>>
>>Compiler writers agree on most of these things, so in reality these things are
>>extremely well defined. Basically nobody cares about what the C standard says
>
> This is true in practice.
>
>>exactly as long as their code compiles.
>
> Yes.  Actually as long as the behaviour of the compiler is known documented and repeatable the standard does not 
> matter in reality.  Most embedded compilers are not ISO-C99 compliant but mostly ISO-C90/95 with compiler and target 
> extensions.

Much of this has to be documented to be conformant. Most compilers also
document details of structure layout, language extensions, ABIs etc.

I have seen very little C99-only code, although most compilers do support
various C99 features in C90 mode. Long long is a good example, we did
it years before C99.

>>If it doesn't work on a particular compiler,
>>it is that compiler's fault. I know, I have dealt with angry customers with millions of
>>lines of code that didn't compile on our expensive but strict ANSI C compiler...
>
> I assume you mean ISO-C compiler. Which standard? C90, C95, C99?

This was C89, the first ANSI C standard. We used -ansi and -c89 options
for a long time, even after ISO C99.

> I do have an email  where a user says:
>
> "We have moved from abc compiler to XYZ compiler. We used to compile with abc and get no errors. We now using xyz 
> compiler we get lots of errors. We think this is because your xyz compiler is more strict than the abc compiler.
>
> Please can you supply us a version of the xyz compiler with a less strict parser."

Sounds fairly typical of a customer indeed. It's impossible to even try to talk them
into fixing their code, as it works on any other compiler they tried. So you've got
to fix the compiler or go out of business. Not a hard choice...

Wilco 


0
4/25/2008 3:44:17 PM
Nils wrote:
> But do you do if you need them anyway? I need *lots* of them, so in
> despair I've just created this monster of unreadable code:
> 
> int ArithmeticShiftRight (int value, unsigned int shift)
> {
      /* Not sure whether that passes your MISRA checker: */
      return (int) ((unsigned long long) value >> shift);
> }

That aside, MISRA usually allows you to deviate from a rule if you have
a good reason. This is to make you think about whether you really need
it. Arithmetic shifts would be a good thing to answer "yes" to that
question.

The function could finally even look like this:
  int ArithmeticShiftRight (int value, unsigned int shift)
  {
  #if ((-1) >> 1) == -1
     return value >> shift;
  #else
  #  error Port me!
  #endif
  }
which would make your code portable under all practical definitions
known to me.


  Stefan

0
stefan.news (242)
4/25/2008 5:26:16 PM
Nils wrote:

> However, it does not work if value is negative because  (-7/2) != 
> (-7>>1). 

You can't know that.  You can't know if two things are unequal without a 
reliable source defining the value for either of them.  -7>>1 causes 
undefined behaviour in a C program.  So every assumption about its 
result is wrong by default.

And guess what: the result of (-7/2) is unkown, too! Technically, at 
least as of C90, which still is the effectively valid definition for 
many of us, it's implementation-defined whether signed division rounds 
towards negative infinity or zero.  So it could be -4 as easily as it 
could be -3.  C99 changed this.  Now it's required to be -3.
0
HBBroeker (925)
4/25/2008 7:02:51 PM
David Brown wrote:

> Is the rounding of shifts like this well defined in C?

_Nothing_ about shifts of negative values is defined _at_all_ in C.  For 
all you know, the machine could catch fire if ever you try it on a 
Tuesday between 12:34:56 h and 12:36:54h (Hawaiian time).

Rounding as a concept is inapplicable to non-arithmetic operators. 
There is no full-precision intermediate result, thus nothing to be rounded.

> I can't remember the exact rules off-hand -

Not surprisingly --- nothing there to be remembered.

> perhaps that's why MISRA doesn't like right shifts of signed
> integers!

You betcha.
0
HBBroeker (925)
4/25/2008 7:09:42 PM
Wilco Dijkstra wrote:

> There is no compiler that doesn't correctly implement signed arithmetic.

That's beside the point --- shifting is not an arithmetic operation.

Nor is there even a definition of "correct" in place for shifting 
negative numbers.  If there were, there would never been a need to 
invent the terms "arithmetic shift" and "logical shift".

> Nobody could get away with creating a compiler that can't compile existing
> code.

The problem is not with compiling the code --- it's what the compiled 
code will actually do.
0
HBBroeker (925)
4/25/2008 7:14:25 PM
On Fri, 25 Apr 2008 12:52:32 GMT, "Richard Phillips"
<raphillips@ntlworld.com> wrote:

>
>This is IMO exactly how MISRA should be used.
>I've been obeying MISRA in my coding at work for years (well, sort of), 
>while there are some things I think are very good (e.g. it makes you think 
>very carefully about casting and potential overflows, it doesn't like magic 
>numbers, etc etc), there are some things I get annoyed at, such as:
>
>* You're not supposed to use "goto".  Avoiding this when you're learning to 
>write code is good practise, but it's very useful in a limited set of 
>circumstances, if used properly.  I remember a manager of mine telling a 
>work colleague once that using "goto" was bad practise, I then showed my 
>colleague my copy of K+R which basically put him right.

IMHO, gotos are fine for jumping forward, but jumping backwards makes
it very hard to follow the program logic. Some looping control
structure can be used to repeat previously executed code. 

I have used this principle since the FORTRAM IV days, in which the
only block control structure was the DO-loop :-).

Paul

0
keinanen (1068)
4/25/2008 7:21:02 PM
"Hans-Bernhard Br�ker" <HBBroeker@t-online.de> wrote in message news:futai4$ine$03$1@news.t-online.com...
> Wilco Dijkstra wrote:
>
>> There is no compiler that doesn't correctly implement signed arithmetic.
>
> That's beside the point --- shifting is not an arithmetic operation.

With arithmetic I meant all operators, including logical, relational, additive,
conversions etc.

> Nor is there even a definition of "correct" in place for shifting negative numbers.  If there were, there would never 
> been a need to invent the terms "arithmetic shift" and "logical shift".

The correct way to shift a signed number is to use an arithmetic shift.
The correct way to shift an unsigned number is to use a logical shift.
This stuff is pretty trivial and well defined. No compiler gets this wrong.

>> Nobody could get away with creating a compiler that can't compile existing
>> code.
>
> The problem is not with compiling the code --- it's what the compiled code will actually do.

You obviously compile to execute... It's well defined what a compiler will do.
If it didn't give the right answer the compiler would be considered broken.

Wilco 


0
4/25/2008 8:00:54 PM
Hans-Bernhard Br�ker schrieb:
> Nils wrote:
> 
>> However, it does not work if value is negative because  (-7/2) != 
>> (-7>>1). 
> 
> You can't know that.  You can't know if two things are unequal without a 
> reliable source defining the value for either of them.  -7>>1 causes 
> undefined behaviour in a C program.  So every assumption about its 
> result is wrong by default.

Yes, you're formally right of course. I have no reference except what 
works in practice.

Name me one CPU/system that:

  a. Does signed arithmetic in one's complement.
  b. a c-compiler exists for that architectue.
  c. Has any significance except nostalgia/historic reasons.

Yes, I'm nitpicking, but so are you :-)

Nils
0
4/25/2008 8:30:13 PM
Wilco Dijkstra wrote:
> "Chris H" <chris@phaedsys.org> wrote:
>
.... snip ...
> 
>> I do have an email  where a user says:
>>
>> "We have moved from abc compiler to XYZ compiler. We used to
>> compile with abc and get no errors. We now using xyz compiler
>> we get lots of errors. We think this is because your xyz compiler
>> is more strict than the abc compiler.
>>
>> Please can you supply us a version of the xyz compiler with a
>> less strict parser."
> 
> Sounds fairly typical of a customer indeed. It's impossible to
> even try to talk them into fixing their code, as it works on any
> other compiler they tried. So you've got to fix the compiler or go
> out of business. Not a hard choice...

If your errors/warnings emit a number, and then haul up an error
message via an index into an auxiliary file, you can soften those
messages as much as you wish without doing anything special.  That
is also language independant.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/25/2008 8:50:23 PM
Nils wrote:
> Name me one CPU/system that:
> 
>  a. Does signed arithmetic in one's complement.
>  b. a c-compiler exists for that architectue.
>  c. Has any significance except nostalgia/historic reasons.
> 
> Yes, I'm nitpicking, but so are you :-)

If so, you just lost this nit-picking contest. ;->

"significance except nostalgia/history" is completely worthless as a 
nit-picking tool.  It's  an impossibly vague phrase that, if you really 
look at it, means nothing at all.
0
HBBroeker (925)
4/25/2008 9:29:59 PM
Hans-Bernhard Br�ker schrieb:
> Wilco Dijkstra wrote:
> 
>> There is no compiler that doesn't correctly implement signed arithmetic.
> 
> That's beside the point --- shifting is not an arithmetic operation.

Oh well.

But why does for example the java language explicitly defines a signed 
right-shift operator? I think the language designers learned from the 
c-language and didn't wanted to make the same mistake again. After all a 
compiler for a hypotetical CPU that can't do the arithmetic shift can 
simulate the operation.

You've asked elsewhere why one would do binary arithmetic on signed 
intergers at the first place. I agree with you that you normally don't 
need that, but there are exceptions. Here is just one:

I have to work on a integer-only CPU and have performance-goals that I 
can't reach with soft-float. My problem calls for more than just integer 
arithmetic.

Requirements are tight, as usual. So what do I do? I write all my 
arithmetic with block-floating-point. That makes the difference in 
performance that brings me over my mips-limit that was negotiated. It 
makes my client happy as well. I do need some signed binary arithmetic 
to get the magic happen though.

Fortunately you can explain such niffy details to the code-review guy 
and get a grant for a misra-warning, but it is cunmbersome to do it 
again and again.

Nils
0
4/25/2008 9:39:50 PM
Richard Phillips schrieb:

> This is IMO exactly how MISRA should be used.
> I've been obeying MISRA in my coding at work for years (well, sort of), 
> while there are some things I think are very good (e.g. it makes you think 
> very carefully about casting and potential overflows, it doesn't like magic 
> numbers, etc etc), there are some things I get annoyed at (...)

100% agree. But I think you miss a very important "real world" part of 
the entire MISRA thing:

You can't simply write "code should not suck" into a contract. If you 
write a piece of code for a company that does safety-critical stuff 
you'll better have some way to measure the code-quality.

This saves both parties of the contract and makes sure you don't get 
into an endless "please change this, I don't like that either, we got a 
warning here, what do you do there" loop.

Noone want's that. It is a efficient way to burn money and make sure 
that the final product never sees the light of day if you don't define 
some kind of standard. In my case that's MISRA with the bullshit omitted 
and some other bullshit added  Since I deliver code the recommendation 
becomes a duty. With all pros and cons.

Btw. I dig most of the recommendations. And I didn't had much problems 
to adopt my code. It was pretty good when I started to care about 
compliance.

There have been some things that made my code more unreadable. Some 
changes even came with a performance costs, but on the other hand I had 
to refactor and re-thing several functions that I would haven't touched.

I came up with a much easier and more performant way to express the same 
thing. And this is good.

   Nils
0
4/25/2008 9:59:50 PM
Hans-Bernhard Br�ker schrieb:
> Nils wrote:
>> Name me one CPU/system that:
>>
>>  a. Does signed arithmetic in one's complement.
>>  b. a c-compiler exists for that architectue.
>>  c. Has any significance except nostalgia/historic reasons.
>>
>> Yes, I'm nitpicking, but so are you :-)
> 
> If so, you just lost this nit-picking contest. ;->
> 
> "significance except nostalgia/history" is completely worthless as a 
> nit-picking tool.  It's  an impossibly vague phrase that, if you really 
> look at it, means nothing at all.

Jep! I have to agree. I just wanted to make sure you don't bring 
obsolete russian architectures into the discussion that do trenary 
arithmetic :-)


Ok. Ignore point c. Any answer to points a and b of my list?

Nils <-- enjoys this nit-picking.
0
4/25/2008 10:12:23 PM
Nils wrote:
> Hans-Bernhard Br�ker schrieb:
>
.... snip ...
>
>> You can't know that.  You can't know if two things are unequal
>> without a reliable source defining the value for either of them. 
>> -7>>1 causes undefined behaviour in a C program.  So every
>> assumption about its result is wrong by default.
> 
> Yes, you're formally right of course. I have no reference except
> what works in practice.
> 
> Name me one CPU/system that:
>   a. Does signed arithmetic in one's complement.
>   b. a c-compiler exists for that architectue.
>   c. Has any significance except nostalgia/historic reasons.
> 
> Yes, I'm nitpicking, but so are you :-)

Yes, you are, but no, he's not.  Shifts on negative values are
undefined behaviour on any system.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/25/2008 10:15:15 PM
"Wilco Dijkstra" <Wilco_dot_Dijkstra@ntlworld.com> wrote in message 
news:MO7Qj.70230$kN5.49223@newsfe1-gui.ntli.net...
> MISRA has some good rules
> but there are a lot of bad ones as well. It's best to pick a subset - 
> the last
> time I looked at it I threw out more than half of the rules.

I totally agree; that's exactly my attitude. MISRA is good, defensive 
common sense designed by a committee ;).

Re the OP's issue: I'd isolate myself from the underlying language 
(whatever it may be) by decomposition - by encapsulating the function in 
a subroutine. A shift is a trick for a fast integer divide or mulitply 
by 2. So I'd write something like:

int  fast_divide_by_two( int )

and in the simplest case, I'd use a shift. On MISRA, I'd use something 
more complex - but it'd still be readable, since my intention is clear. 
(Hell, use a macro if you prefer. Hell, factor it out and make it 
platform-specific. Hell, so long as it's clear, I don't care about 
complex - I can always decompose it out.)

/me now poorer by 2c

Steve


0
steve4412 (879)
4/25/2008 11:15:46 PM
"Richard Phillips" <raphillips@ntlworld.com> wrote in message 
news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
> * You're not supposed to use "goto".  Avoiding this when you're 
> learning to write code is good practise, but it's very useful in a 
> limited set of circumstances, if used properly.  I remember a manager 
> of mine telling a work colleague once that using "goto" was bad 
> practise, I then showed my colleague my copy of K+R which basically 
> put him right.
>
> * You're not supposed to exit from a controlled loop prematurely.

Avoiding "goto" means avoiding unstructured design (i.e. using only only 
closed structures - one start, one end, any other context signalled by 
other means than programme flow).

Exiting a control loop prematurely is not a case of a goto - it's still 
a case of one start, one end. It just avoids a layer of indenting and 
promotes readability.

Things like jump tables are not lists of gotos - they're a list of 
(derefenced, if you insist) function pointers.

Summary: avoiding goto as a design concept is a Good Thing. Avoiding 
gotos as a means of implementing good structure is simply 
misunderstanding the point. I've seen (possibly on this ng) someone 
defending goto on the basis that CPUs only know about branches and jumps 
anyway. Follocks.

 It's *not* about implementation. It's about design. If you use gotos to 
implement an IF THEN ELSE ENDIF structure, I could care less. It's still 
structured.

Bottom line: uncontrolled program flow is a Bad Thing. If you can't look 
at a chunk of code and know the answer to the question "How did I get 
here?" - warning!

Steve
(another 2c poorer) 


0
steve4412 (879)
4/25/2008 11:29:33 PM
"Stefan Reuther" <stefan.news@arcor.de> wrote in message 
news:futb8o.e8.1@stefan.msgid.phost.de...
> Nils wrote:
>> But do you do if you need them anyway? I need *lots* of them, so in
>> despair I've just created this monster of unreadable code:
>>
>> int ArithmeticShiftRight (int value, unsigned int shift)
>> {
>      /* Not sure whether that passes your MISRA checker: */
>      return (int) ((unsigned long long) value >> shift);
>> }
>
> That aside, MISRA usually allows you to deviate from a rule if you 
> have
> a good reason. This is to make you think about whether you really need
> it. Arithmetic shifts would be a good thing to answer "yes" to that
> question.
>
> The function could finally even look like this:
>  int ArithmeticShiftRight (int value, unsigned int shift)
>  {
>  #if ((-1) >> 1) == -1
>     return value >> shift;
>  #else
>  #  error Port me!
>  #endif
>  }
> which would make your code portable under all practical definitions
> known to me.

I totally agree - I do exactly this as a matter of routine. I strongly 
encourage the use of macro-level platform traps which say "if this isn't 
the platform I made allowances for and assumptions about, then yell - 
don't just compile incorrectly".

Steve


0
steve4412 (879)
4/25/2008 11:34:39 PM
On 2008-04-25, Nils <n.pipenbrinck@cubic.org> wrote:
> Hans-Bernhard Br�ker schrieb:
>> Wilco Dijkstra wrote:
>> 
>>> There is no compiler that doesn't correctly implement signed arithmetic.
>> 
>> That's beside the point --- shifting is not an arithmetic operation.
>
> Oh well.
>
> But why does for example the java language explicitly defines a signed 
> right-shift operator?

For the same reason that CPUs have a logical shift right and an
arithmatic shift right instruction: despite the claim to the
contrary, shifting is considered by almost everybody to be an
arithmetic operation.

-- 
Grant Edwards                   grante             Yow!  I was giving HAIR
                                  at               CUTS to th' SAUCER PEOPLE
                               visi.com            ... I'm CLEAN!!
0
grante (5416)
4/26/2008 12:48:09 AM
Steve at fivetrees wrote:
> 
.... snip ...
> 
> Avoiding "goto" means avoiding unstructured design (i.e. using
> only only closed structures - one start, one end, any other
> context signalled by other means than programme flow).
> 
> Exiting a control loop prematurely is not a case of a goto -
> it's still a case of one start, one end. It just avoids a layer
> of indenting and promotes readability.
> 
> Things like jump tables are not lists of gotos - they're a list
> of (derefenced, if you insist) function pointers.
> 
> Summary: avoiding goto as a design concept is a Good Thing.
> Avoiding gotos as a means of implementing good structure is
> simply misunderstanding the point. I've seen (possibly on this
> ng) someone defending goto on the basis that CPUs only know
> about branches and jumps anyway. Follocks.

Not according to me.  Consider the following function outline:

int foo( /* whatever */ ) {
   int errmk = 0;
   FILE *f1, *f2, *fw;

   if      (!(f1 = fopen(f1name, "r")) {
      errmk = 1; goto f1bad;
   }
   else if (!(f2 = fopen(f2name, "r")) {
      errmk = 2; goto f2bad;
   }
   else if (!(fw = fopen(fwname, "w")) {
      errmk = 3;  goto fwbad;
   }
   else {
      /* files open, play appropriate games */
   }
   fputs(fwendln, fw);
   fclose(fw);
fwbad:
   fclose(f2);
f2bad:
   fclose(f1);
f1bad:
   return errmk;
}
 
There are lots of undetected errors left, that is an outline.  Yes,
there are other ways to handle it.  

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.

** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/26/2008 1:32:28 AM
In message <6_6dnY2wrOW5-4_VnZ2dnUVZ8uGdnZ2d@pipex.net>, Steve at 
fivetrees <steve@NOSPAMTAfivetrees.com> writes
>"Wilco Dijkstra" <Wilco_dot_Dijkstra@ntlworld.com> wrote in message
>news:MO7Qj.70230$kN5.49223@newsfe1-gui.ntli.net...
>> MISRA has some good rules
>> but there are a lot of bad ones as well. It's best to pick a subset -
>> the last
>> time I looked at it I threw out more than half of the rules.
>
>I totally agree; that's exactly my attitude. MISRA is good, defensive
>common sense designed by a committee ;).

I agree... It would be perfect but the others on the committee get in my 
way :-)

The MISRA-C* rules are Engineering Guidance NOT a religion.  You can 
deviate any or all of them as long as you can put up a good deviation 
that will make sense to a jury in court in 3 years time....

No I am not using scare tactics. I am trying to point out that 
deviations should not be something that (like source code) that you and 
the programmer next to you thinks makes sense now but makes no sense to 
some one else 3 weeks later. ALL Deviations should be reviewed ater a 
period of time to see if the still make sense.

* Please not "MISRA" but MISRA-C or you will confuse it with MISRA-C++ 
launched on 5th June at the Safety Critical Systems Club event in London
http://www.scsc.org.uk/diary.html?opt=detail&id=70

I can say this as the MISRA-C++ is actually finished and going to / is 
at the printers. CAVEAT:- I had nothing to do with this one! :-)

Also there are the MISRA-Guidelines (parts 1-8) published 1994 and the 
MISRA-Safety-Analyasis, and the MISRA-Autocode standards (three parts 
issued so far.) There will also be a MISRA-Languages document on common 
problems across languages


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/26/2008 6:48:18 AM
In message <SuCdnb4TBovD9I_VnZ2dnUVZ8uadnZ2d@pipex.net>, Steve at 
fivetrees <steve@NOSPAMTAfivetrees.com> writes
>"Richard Phillips" <raphillips@ntlworld.com> wrote in message
>news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
>> * You're not supposed to use "goto".  Avoiding this when you're
>> learning to write code is good practise, but it's very useful in a
>> limited set of circumstances, if used properly.  I remember a manager
>> of mine telling a work colleague once that using "goto" was bad
>> practise, I then showed my colleague my copy of K+R which basically
>> put him right.
>>
>> * You're not supposed to exit from a controlled loop prematurely.
>
>Avoiding "goto" means avoiding unstructured design (i.e. using only only
>closed structures - one start, one end, any other context signalled by
>other means than programme flow).

However as with all things there are a few exceptions where got is the 
cleanest solution.  In those cases you need to deviate and be able to 
stand up in court in 3 years time with your deviation.


Intestinally the "goto" is bad" came from a paper by Dykstra  (not Wilco 
:-) and AFAIK no one has really challenged it but just taken it as read. 
I know some people are doing some work into it to see if it really is 
that bad.

I suspect the trouble will be that 90% of those who want to use goto are 
the sort of people who will write appalling code anyway and 90% of those 
who think goto should be banned would only ever use it very sensibly.

So it is a self fore filling prophesy:

90% of those who want to use it should not
90% of those who could use it properly will not.

The group who want to use it and would use it properly are now a very 
small number.



-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/26/2008 6:57:10 AM
Chris H wrote:
> In message <kukQj.59491$h65.48326@newsfe2-gui.ntli.net>, Richard
> Phillips <raphillips@ntlworld.com> writes
>>
>> This is IMO exactly how MISRA should be used.
>> I've been obeying MISRA in my coding at work for years (well, sort
>> of), while there are some things I think are very good (e.g. it
>> makes you think very carefully about casting and potential
>> overflows, it doesn't like magic numbers, etc etc), there are some
>> things I get annoyed at, such as: * You're not supposed to use "goto". 
>> Avoiding this when you're
>> learning to write code is good practise, but it's very useful in a
>> limited set of circumstances, if used properly.
>
> This is true.
>
>> I remember a manager of mine telling a
>> work colleague once that using "goto" was bad practise, I then
>> showed my colleague my copy of K+R which basically put him right.
>
>
> Maybe. IT was AFAIK Dykstra who said goto was bad and no one has
> challenged that with a convincing strategy for using goto. Mainly
> because the majority who do use it tend to miss use it.  So it should
> not normally be used but...
>
>> * You're not supposed to exit from a controlled loop prematurely.
>>
>> * ...  Hmm, actually I could go on for a while.  Suffice to say,
>> there are a few things...!
>
> All of the MISRA rules are good *some* of the time. Where they are not
> it is up to you to come up with a project specific reason why not.

This is fair enough.  I can see the sense behind most rules some of the 
time!

>
>> I've seen some tidy well-written code turned inside out and made
>> semi-unreadable by trying to make it MISRA compliant.
>
> I know what you mean it is the "tick the box" brigade who want to say
> we are MISRA compliant without actually using any Engineering thought
> on it.

Like I say, in my company, even though I know realise that we are allowed to 
deviate (and deviations should be documented), when I first joined I 
certainly had a different impression.  I know I wasn't the only one because 
I could see some of the crazy things others were doing in the name of MISRA. 
To my knowledge though I don't think we produce a "MISRA compliance and 
deviations" doc per project, perhaps I will suggest this next week to my 
manager!

>
>>  If it makes code more
>> complicated (and more error-prone) then it's doing the opposite of
>> what's intended.
>
> Hence MIStRAy-C A spoof on MISRA-C
>
> http://www.phaedsys.demon.co.uk/chris/mistrayc/

Thanks, I'll take a look at that...

>
>> I had a chat with a manager of mine about this once and he said
>> that MISRA was basically a guide, obey it if you can, but if there
>> is a problem with doing this then all that was needed was to
>> document the non-compliances.  For me, this is a far more sensible
>> approach.
>
> I personally believe this is the way it is meant to be used.

Makes sense to me, but I think there seems to be some misunderstanding out 
there.

>
>> Sort out
>> the obvious clangers, but don't turn good neat code into jumbled
>> unreadable rubbish just to satisfy MISRA!!
>
> Any suggestions on how the MISRA team can stop people doing this All
> methods must be legal under the UN human rights and Geneva
> conventions. Water-boarding or stringing up by their thumbs for 
> recalcitrant programmers and managers  may be deserved and satisfying
> but we can't writ it in to a coding standard :-)
>
>> The problem is there is some misunderstanding here.  MISRA lists
>> it's rules as "recommended" and "required" (or something like that),
>> which makes it sound like "required" rules MUST be obeyed, which
>> doesn't appear to be the case from what I now understand.
>
> It was required and advisory. IE those that should normally be used
> and those which are useful a lot of the time.
>
> Any suggestions for a different nomenclature?

Hmm, I'd have to have a copy of the MISRA guidelines in front of me to 
answer this properly, perhaps I'm being unfair on the guidelines because 
I've tended to look at the rules themselves rather than read the doc from 
cover to cover, if I had maybe I'd have a different impression.  Perhaps 
"required" and "advisory" are defined in there properly somewhere?
However, that said, "required" to me suggests I must obey at all times, it's 
"required" without deviation!  "Advisory" suggests to me what you say 
"required" actually means.
I'll have a read of the guidelines on Monday and have a think about this, if 
I'm going to suggest an alternative I want to make sure I put some thought 
into it...


0
raphillips (57)
4/26/2008 10:14:48 AM
Paul Keinanen wrote:
> On Fri, 25 Apr 2008 12:52:32 GMT, "Richard Phillips"
> <raphillips@ntlworld.com> wrote:
>
>>
>> This is IMO exactly how MISRA should be used.
>> I've been obeying MISRA in my coding at work for years (well, sort
>> of), while there are some things I think are very good (e.g. it
>> makes you think very carefully about casting and potential
>> overflows, it doesn't like magic numbers, etc etc), there are some
>> things I get annoyed at, such as:
>>
>> * You're not supposed to use "goto".  Avoiding this when you're
>> learning to write code is good practise, but it's very useful in a
>> limited set of circumstances, if used properly.  I remember a
>> manager of mine telling a work colleague once that using "goto" was
>> bad practise, I then showed my colleague my copy of K+R which
>> basically put him right.
>
> IMHO, gotos are fine for jumping forward, but jumping backwards makes
> it very hard to follow the program logic. Some looping control
> structure can be used to repeat previously executed code.
>
> I have used this principle since the FORTRAM IV days, in which the
> only block control structure was the DO-loop :-).
>
> Paul

I was deliberately unspecific in my original post, but the one situation 
I've found a goto is a perfect solution is neatly getting out of deeply 
nested conditional code (i.e. jumping forward!).  I've found that this 
situation occurs often when dealing with communications.  Without using 
goto, you need lots of extra code to get back out.

R. 


0
raphillips (57)
4/26/2008 10:28:45 AM
Nils wrote:
> Richard Phillips schrieb:
>
>> This is IMO exactly how MISRA should be used.
>> I've been obeying MISRA in my coding at work for years (well, sort
>> of), while there are some things I think are very good (e.g. it
>> makes you think very carefully about casting and potential
>> overflows, it doesn't like magic numbers, etc etc), there are some
>> things I get annoyed at (...)
>
> 100% agree. But I think you miss a very important "real world" part of
> the entire MISRA thing:
>
> You can't simply write "code should not suck" into a contract. If you
> write a piece of code for a company that does safety-critical stuff
> you'll better have some way to measure the code-quality.
>
> This saves both parties of the contract and makes sure you don't get
> into an endless "please change this, I don't like that either, we got
> a warning here, what do you do there" loop.
>
> Noone want's that. It is a efficient way to burn money and make sure
> that the final product never sees the light of day if you don't define
> some kind of standard. In my case that's MISRA with the bullshit
> omitted and some other bullshit added  Since I deliver code the
> recommendation becomes a duty. With all pros and cons.
>
> Btw. I dig most of the recommendations. And I didn't had much problems
> to adopt my code. It was pretty good when I started to care about
> compliance.
>
> There have been some things that made my code more unreadable. Some
> changes even came with a performance costs, but on the other hand I
> had to refactor and re-thing several functions that I would haven't
> touched.
> I came up with a much easier and more performant way to express the
> same thing. And this is good.
>
>   Nils

Fair point.  I suppose MISRA does give a useful yardstick when measuring the 
"quality" of code.  I'll confess I hadn't looked at it from this viewpoint.

One thing I will say which you've touched upon here, is that I've tightened 
up on my code quality (not that it was deliberately bad before!) because I'm 
aware that MISRA might not like something.  I tend to write code that is 
MISRA-compliant (most of the time) without even really thinking about it 
now.
So I think on the whole, MISRA has perhaps been more useful than I give it 
credit for.  But I stand by my original arguement though; blindly following 
the rules (as I've seen done) is NOT "advisory"!

R. 


0
raphillips (57)
4/26/2008 10:35:27 AM
Steve at fivetrees wrote:
> "Richard Phillips" <raphillips@ntlworld.com> wrote in message
> news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
>> * You're not supposed to use "goto".  Avoiding this when you're
>> learning to write code is good practise, but it's very useful in a
>> limited set of circumstances, if used properly.  I remember a manager
>> of mine telling a work colleague once that using "goto" was bad
>> practise, I then showed my colleague my copy of K+R which basically
>> put him right.
>>
>> * You're not supposed to exit from a controlled loop prematurely.
>
> Avoiding "goto" means avoiding unstructured design (i.e. using only
> only closed structures - one start, one end, any other context
> signalled by other means than programme flow).

Sorry, I think that's just wrong.  If K+R think it's ok and include it in 
the language, I think there must be some point to it.
The one case I've encountered where it's "needed" is deeply nested 
conditional code.  Often encoutered in communications, where you need to 
test lots of conditions before a packet of data is "accepted".  If the data 
is rejected at the final check, goto gets you right back out gracefully 
without lots of extra checking code.

>
> Exiting a control loop prematurely is not a case of a goto - it's
> still a case of one start, one end. It just avoids a layer of
> indenting and promotes readability.
>

I never said goto should be used in this instance.

> Things like jump tables are not lists of gotos - they're a list of
> (derefenced, if you insist) function pointers.
>
> Summary: avoiding goto as a design concept is a Good Thing.

In most cases, yes.  But see above.

Avoiding
> gotos as a means of implementing good structure is simply
> misunderstanding the point. I've seen (possibly on this ng) someone
> defending goto on the basis that CPUs only know about branches and
> jumps anyway. Follocks.
>
> It's *not* about implementation. It's about design. If you use gotos
> to implement an IF THEN ELSE ENDIF structure, I could care less. It's
> still structured.
>
> Bottom line: uncontrolled program flow is a Bad Thing. If you can't
> look at a chunk of code and know the answer to the question "How did
> I get here?" - warning!
>
> Steve
> (another 2c poorer)


0
raphillips (57)
4/26/2008 10:44:28 AM
Chris H wrote:
> In message <SuCdnb4TBovD9I_VnZ2dnUVZ8uadnZ2d@pipex.net>, Steve at
> fivetrees <steve@NOSPAMTAfivetrees.com> writes
>> "Richard Phillips" <raphillips@ntlworld.com> wrote in message
>> news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
>>> * You're not supposed to use "goto".  Avoiding this when you're
>>> learning to write code is good practise, but it's very useful in a
>>> limited set of circumstances, if used properly.  I remember a
>>> manager of mine telling a work colleague once that using "goto" was
>>> bad practise, I then showed my colleague my copy of K+R which
>>> basically put him right.
>>>
>>> * You're not supposed to exit from a controlled loop prematurely.
>>
>> Avoiding "goto" means avoiding unstructured design (i.e. using only
>> only closed structures - one start, one end, any other context
>> signalled by other means than programme flow).
>
> However as with all things there are a few exceptions where got is the
> cleanest solution.  In those cases you need to deviate and be able to
> stand up in court in 3 years time with your deviation.
>
>
> Intestinally the "goto" is bad" came from a paper by Dykstra  (not
> Wilco :-) and AFAIK no one has really challenged it but just taken it
> as read. I know some people are doing some work into it to see if it
> really is that bad.
>
> I suspect the trouble will be that 90% of those who want to use goto
> are the sort of people who will write appalling code anyway and 90%
> of those who think goto should be banned would only ever use it very
> sensibly.
> So it is a self fore filling prophesy:
>
> 90% of those who want to use it should not
> 90% of those who could use it properly will not.
>
> The group who want to use it and would use it properly are now a very
> small number.

Well said!!  Agree with that 100%.

R. 


0
raphillips (57)
4/26/2008 10:47:17 AM

Steve at fivetrees wrote:

> "Stefan Reuther" <stefan.news@arcor.de> wrote in message
> news:futb8o.e8.1@stefan.msgid.phost.de...
> > Nils wrote:
> >> But do you do if you need them anyway? I need *lots* of them, so in
> >> despair I've just created this monster of unreadable code:
> >>
> >> int ArithmeticShiftRight (int value, unsigned int shift)
> >> {
> >      /* Not sure whether that passes your MISRA checker: */
> >      return (int) ((unsigned long long) value >> shift);
> >> }
> >
> > That aside, MISRA usually allows you to deviate from a rule if you
> > have
> > a good reason. This is to make you think about whether you really need
> > it. Arithmetic shifts would be a good thing to answer "yes" to that
> > question.
> >
> > The function could finally even look like this:
> >  int ArithmeticShiftRight (int value, unsigned int shift)
> >  {
> >  #if ((-1) >> 1) == -1
> >     return value >> shift;
> >  #else
> >  #  error Port me!
> >  #endif
> >  }
> > which would make your code portable under all practical definitions
> > known to me.
>
> I totally agree - I do exactly this as a matter of routine. I strongly
> encourage the use of macro-level platform traps which say "if this isn't
> the platform I made allowances for and assumptions about, then yell -
> don't just compile incorrectly".

I agree with the idea but be careful of the implementation.
The math executed in
#if ((-1) >> 1) == -1
is done so with the preprocessor and not the runtime
environment. They may not be the same.

I have seen two or three run time test routines written to
identify compiler features and how they work. This
would be a good place to use this type of code.
I will try to track down a url reference.

Walter..



0
walter20 (887)
4/26/2008 10:56:56 AM
In message <PzDQj.70642$kN5.46880@newsfe1-gui.ntli.net>, Richard 
Phillips <raphillips@ntlworld.com> writes
>Fair point.  I suppose MISRA does give a useful yardstick when measuring the
>"quality" of code.  I'll confess I hadn't looked at it from this viewpoint.
>
>One thing I will say which you've touched upon here, is that I've tightened
>up on my code quality (not that it was deliberately bad before!) because I'm
>aware that MISRA might not like something.  I tend to write code that is
>MISRA-compliant (most of the time) without even really thinking about it
>now.

This is what we were hoping for. It is a bit like Pavlovs dogs. (Bell 
rings-> get food:dogs salivate. evetualy dogs salivate when bell rings 
even if no food)

If people keep getting MISRA-C errors flanged they will eventually stop 
writing code with MISRA-C errors in it (as much as any one write bug 
free SW)

This saves time and effort and produces safer more reliable code faster.

Static analysis such as PC-Lint will have a similar effect.

BTW you should use a static analyser that checks MISRA rules not a tool 
that ONLY checks for MISRA rules. (See section 4.3)

>So I think on the whole, MISRA has perhaps been more useful than I give it
>credit for.

If we can raise the level of the masses by 1 or 2 points then that is a 
worth while goal.

>  But I stand by my original arguement though; blindly following
>the rules (as I've seen done) is NOT "advisory"!

I agree.

-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/26/2008 11:12:11 AM
In message <gIDQj.112578$5i5.4642@newsfe6-gui.ntli.net>, Richard 
Phillips <raphillips@ntlworld.com> writes
>Steve at fivetrees wrote:
>> "Richard Phillips" <raphillips@ntlworld.com> wrote in message
>> news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
>>> * You're not supposed to use "goto".  Avoiding this when you're
>>> learning to write code is good practise, but it's very useful in a
>>> limited set of circumstances, if used properly.  I remember a manager
>>> of mine telling a work colleague once that using "goto" was bad
>>> practise, I then showed my colleague my copy of K+R which basically
>>> put him right.
>>>
>>> * You're not supposed to exit from a controlled loop prematurely.
>>
>> Avoiding "goto" means avoiding unstructured design (i.e. using only
>> only closed structures - one start, one end, any other context
>> signalled by other means than programme flow).
>
>Sorry, I think that's just wrong.  If K+R think it's ok and include it in
>the language, I think there must be some point to it.

That is blind faith some 35 years on.   The language and SW Engineering 
have moved a long way since then.  Also  C was designed as a language 
for expert programmers.

Incidentally you do not use K&R C... There have been TWO Major revisions 
of C since K&R1

Things were changed to "improve" them but nothing was removed simply to 
keep backward compatibility even if it was not a good idea for general 
use. Some things in C are banned outright for safety critical or high 
reliability code but they are still in the base language standard.


>The one case I've encountered where it's "needed"

There will always be an exception.  Only Death and Taxes are inviolate.


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/26/2008 11:19:24 AM
Walter Banks wrote:
> Steve at fivetrees wrote:
>>"Stefan Reuther" <stefan.news@arcor.de> wrote in message
>>> #if ((-1) >> 1) == -1
>>>    return value >> shift;
>>> #else
>>> #  error Port me!
>>> #endif
>>> }
>>>which would make your code portable under all practical definitions
>>>known to me.
>>
>>I totally agree - I do exactly this as a matter of routine. I strongly
>>encourage the use of macro-level platform traps which say "if this isn't
>>the platform I made allowances for and assumptions about, then yell -
>>don't just compile incorrectly".
> 
> I agree with the idea but be careful of the implementation.
> The math executed in
> #if ((-1) >> 1) == -1
> is done so with the preprocessor and not the runtime
> environment. They may not be the same.

If I read ISO 9899:1999 correctly, they have to be the same.

6.10.1p3: "The resulting tokens compose the controlling constant
  expression which is evaluated according to the rules of 6.6, except
  that all signed integer types and all unsigned integer types act as if
  they have the same representation as, respectively, the types intmax_t
  and uintmax_t defined in the header <stdint.h>."

6.6p11: "The semantic rules for the evaluation of a constant expression
  are the same as for nonconstant expressions."

Im quite optimistic that, in year 18 after ISO C, pre-standard
preprocessors have fallen into disuse :-)


  Stefan

0
stefan.news (242)
4/26/2008 11:40:44 AM
On Fri, 25 Apr 2008 16:34:35 +0100, Chris H <chris@phaedsys.org>
wrote:

>In message <kukQj.59491$h65.48326@newsfe2-gui.ntli.net>, Richard 
>Phillips <raphillips@ntlworld.com> writes
>>
>>This is IMO exactly how MISRA should be used.
>>I've been obeying MISRA in my coding at work for years (well, sort of),
>>while there are some things I think are very good (e.g. it makes you think
>>very carefully about casting and potential overflows, it doesn't like magic
>>numbers, etc etc), there are some things I get annoyed at, such as:
>>
>>* You're not supposed to use "goto".  Avoiding this when you're learning to
>>write code is good practise, but it's very useful in a limited set of
>>circumstances, if used properly.
>
>This is true.
>
>>I remember a manager of mine telling a
>>work colleague once that using "goto" was bad practise, I then showed my
>>colleague my copy of K+R which basically put him right.
>
>
>Maybe. IT was AFAIK Dykstra who said goto was bad and no one has 
>challenged that with a convincing strategy for using goto. Mainly 
>because the majority who do use it tend to miss use it.  So it should 
>not normally be used but...

I have only been working for more than three decades in the IT sector,
so I am youngster compared to many in this NG, but the only time I
have seen bad goto spaghetti code, was a factory management package
written in the late 1970's in COBOL. 

Of course, the situation might have been much worse in the 1960's, but
why make such fuss about gotos in this millennium ?

Paul

0
keinanen (1068)
4/26/2008 1:36:49 PM
Walter Banks wrote:

> I agree with the idea but be careful of the implementation.
> The math executed in
> #if ((-1) >> 1) == -1
> is done so with the preprocessor and not the runtime
> environment. They may not be the same.

It's way worse than that.  Shifting negative values at runtime causes 
undefined behaviour.  I.e. even if they come out the same in the test, 
it can suddenly behave differently in the actual program, but only if 
you called gettimeofday() within 2 seconds before computing (-1)>>1. 
And you'ld have no leg to stand on if you complained about it to the 
compiler maker.  Undefined behaviour means that _all_ bets are off.
0
HBBroeker (925)
4/26/2008 2:27:05 PM
Hans-Bernhard Br�ker wrote:
> Walter Banks wrote:
>> I agree with the idea but be careful of the implementation.
>> The math executed in
>> #if ((-1) >> 1) == -1
>> is done so with the preprocessor and not the runtime
>> environment. They may not be the same.
> 
> It's way worse than that.  Shifting negative values at runtime causes
> undefined behaviour.  I.e. even if they come out the same in the test,
> it can suddenly behave differently in the actual program, but only if
> you called gettimeofday() within 2 seconds before computing (-1)>>1. And
> you'ld have no leg to stand on if you complained about it to the
> compiler maker.  Undefined behaviour means that _all_ bets are off.

'(-1) >> 1' is implementation-defined, not undefined. Implementations
that define it as 'exec("/usr/games/nethack")' are rare.

'1 >> (-1)' is undefined.


  Stefan

0
stefan.news (242)
4/26/2008 3:02:13 PM
Hans-Bernhard Br�ker schrieb:

> It's way worse than that.  Shifting negative values at runtime causes 
> undefined behaviour.  I.e. even if they come out the same in the test, 
> it can suddenly behave differently in the actual program, but only if 
> you called gettimeofday() within 2 seconds before computing (-1)>>1. And 
> you'ld have no leg to stand on if you complained about it to the 
> compiler maker.  Undefined behaviour means that _all_ bets are off.

No - it is not undefined behaviour, it is implementation-defined 
behaviour. This is a big difference because any ISO-compliant compiler 
has to define how they handle these cases. And these behavious don't 
change just because you've called gettimeofday().

You can trust these definitions.


The GCC manual has a nice list of them:

http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/C-Implementation.html#C-Implementation

Nils
0
4/26/2008 3:29:08 PM
In message <4811F36B.FD35B43D@yahoo.com>, CBFalconer 
<cbfalconer@yahoo.com> writes
>Richard Phillips wrote:
>>
>... snip ...
>>
>> The problem is there is some misunderstanding here.  MISRA lists
>> it's rules as "recommended" and "required" (or something like
>> that), which makes it sound like "required" rules MUST be obeyed,
>> which doesn't appear to be the case from what I now understand.
>
>The only 'required' rules are those of the C standard.
>

Absolutely NOT.

(Which C standard? )

-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/26/2008 5:03:42 PM
Stefan Reuther wrote:

> '(-1) >> 1' is implementation-defined, not undefined. 

Sorry.  I mixed that up with the similar case (-1)<<1, which does cause 
undefined behaviour.

> Implementations that define it as 'exec("/usr/games/nethack")' are
> rare.

They would be forbidden, actually.  Running nethack would be undefined 
behaviour.

But notice that it doesn't say anywhere what the implementation is or is 
not allowed to document as its implementation-specified result.  It 
could perform arithmetic shifts on Mondays or in May, logical shifts 
otherwise.
0
HBBroeker (925)
4/26/2008 7:38:42 PM
CBFalconer wrote:
> Nils wrote:
> ... snip ...
>> int ArithmeticShiftRight (int value, unsigned int shift) {
>>    if (shift) {
>>      /* Get unsigned version of value to work with */
>>      unsigned int x = (unsigned int) value;
> 
> This operation is not possible in a standard C system.

Oh, but it is.  Casting from signed to unsigned operates modulo 
(UINT_MAX+1) (C99 6.3.1.3p2).

It's the other way round that isn't well-defined.  The result of casting 
an unsigned number above INT_MAX to integer is implementation-defined.

 > Think about
> what would happen to negative values in sign-magnitude, 1's
> complement, or 2's complement.

The same thing.  The conversion is independent on representation.
0
HBBroeker (925)
4/26/2008 7:42:54 PM
CBFalconer wrote:
> Steve at fivetrees wrote:
> ... snip ...
>> Avoiding "goto" means avoiding unstructured design (i.e. using
>> only only closed structures - one start, one end, any other
>> context signalled by other means than programme flow).
>>
>> Exiting a control loop prematurely is not a case of a goto -
>> it's still a case of one start, one end. It just avoids a layer
>> of indenting and promotes readability.
>>
>> Things like jump tables are not lists of gotos - they're a list
>> of (derefenced, if you insist) function pointers.
>>
>> Summary: avoiding goto as a design concept is a Good Thing.
>> Avoiding gotos as a means of implementing good structure is
>> simply misunderstanding the point. I've seen (possibly on this
>> ng) someone defending goto on the basis that CPUs only know
>> about branches and jumps anyway. Follocks.
> 
> Not according to me.  Consider the following function outline:
> 
> int foo( /* whatever */ ) {
>    int errmk = 0;
>    FILE *f1, *f2, *fw;
> 
>    if      (!(f1 = fopen(f1name, "r")) {
>       errmk = 1; goto f1bad;
>    }
>    else if (!(f2 = fopen(f2name, "r")) {
>       errmk = 2; goto f2bad;
>    }
>    else if (!(fw = fopen(fwname, "w")) {
>       errmk = 3;  goto fwbad;
>    }
>    else {
>       /* files open, play appropriate games */
>    }
>    fputs(fwendln, fw);
>    fclose(fw);
> fwbad:
>    fclose(f2);
> f2bad:
>    fclose(f1);
> f1bad:
>    return errmk;
> }
>  
> There are lots of undetected errors left, that is an outline.  Yes,
> there are other ways to handle it.  
> 

int foo( /* whatever */ ) {
	int errmk = 0;
	FILE *f1, *f2, *fw;
	if (!(f1 = fopen(f1name, "r")) {
		errmk = 1;
	} else {
		if (!(f2 = fopen(f2name, "r")) {
			errmk = 2;
		} else {
			if (!(fw = fopen(fwname, "w")) {
				errmk = 3;
			} else {
				/* Files open */
				fputs(fwendln, fw);
				fclose(fw);
			};
			fclose(f2);
		};
		fclose(f1);
	};
	return errmk;
}

Unless you are using a 40-character wide screen, that version is at 
least as good as your "goto" version.  I've seen people claim that they 
"need" goto's to write good code - I've never actually had the need of 
one in anything I've written.  I've done other "bad" things, such as 
"return" in the middle of loops, but I think "goto" is a bit more 
unstructured than that.  Once you start doing things like jumping in and 
out of variable scopes with goto, you are asking for trouble 
(inefficient code, or even incorrect code).  I don't mean to say that 
all goto's are wrong - just that you'd better have a much better excuse 
than that function before using it.
0
david.brown (580)
4/26/2008 8:04:35 PM

Stefan Reuther wrote:

> Walter Banks wrote:
> > Steve at fivetrees wrote:
> >>"Stefan Reuther" <stefan.news@arcor.de> wrote in message
> >>> #if ((-1) >> 1) == -1
> >>>    return value >> shift;
> >>> #else
> >>> #  error Port me!
> >>> #endif
> >>> }
> >>>which would make your code portable under all practical definitions
> >>>known to me.
> >>
> >>I totally agree - I do exactly this as a matter of routine. I strongly
> >>encourage the use of macro-level platform traps which say "if this isn't
> >>the platform I made allowances for and assumptions about, then yell -
> >>don't just compile incorrectly".
> >
> > I agree with the idea but be careful of the implementation.
> > The math executed in
> > #if ((-1) >> 1) == -1
> > is done so with the preprocessor and not the runtime
> > environment. They may not be the same.
>
> If I read ISO 9899:1999 correctly, they have to be the same.
>
> 6.10.1p3: "The resulting tokens compose the controlling constant
>   expression which is evaluated according to the rules of 6.6, except
>   that all signed integer types and all unsigned integer types act as if
>   they have the same representation as, respectively, the types intmax_t
>   and uintmax_t defined in the header <stdint.h>."
>
> 6.6p11: "The semantic rules for the evaluation of a constant expression
>   are the same as for nonconstant expressions."
>
> Im quite optimistic that, in year 18 after ISO C, pre-standard
> preprocessors have fallen into disuse :-)
>

They are supposed to be and likely are the same.

I know at least one commercial compiler that has the
preprocessor right and the run time wrong. It was
released by a company that should know better
and has been doing this for quite a few years.

Their license doesn't allow benchmark information
to be released without their permission.

w..

0
walter20 (887)
4/26/2008 9:27:14 PM
Hans-Bernhard Br�ker wrote:
> CBFalconer wrote:
>> Nils wrote:
>> ... snip ...
>>> int ArithmeticShiftRight (int value, unsigned int shift) {
>>>    if (shift) {
>>>      /* Get unsigned version of value to work with */
>>>      unsigned int x = (unsigned int) value;
>>
>> This operation is not possible in a standard C system.
> 
> Oh, but it is.  Casting from signed to unsigned operates modulo
> (UINT_MAX+1) (C99 6.3.1.3p2).

I know that, but I didn't write that.  I suspect I snipped in the
wrong places.  Yes, my above answer is nonsense.
> 
> It's the other way round that isn't well-defined.  The result of casting
> an unsigned number above INT_MAX to integer is implementation-defined.
> 
>> Think about what would happen to negative values in sign-magnitude,
>> 1's complement, or 2's complement.
> 
> The same thing.  The conversion is independent on representation.

Same silly reply from me.  Sorry for the foul-up.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/27/2008 1:25:54 AM
Chris H wrote:
> <cbfalconer@yahoo.com> writes
>> Richard Phillips wrote:
>>
>>... snip ...
>>>
>>> The problem is there is some misunderstanding here.  MISRA lists
>>> it's rules as "recommended" and "required" (or something like
>>> that), which makes it sound like "required" rules MUST be obeyed,
>>> which doesn't appear to be the case from what I now understand.
>>
>> The only 'required' rules are those of the C standard.
> 
> Absolutely NOT. (Which C standard? )

Since MISRA is organized around C90/95, that standard.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/27/2008 1:28:31 AM
David Brown wrote:
> CBFalconer wrote:
>> Steve at fivetrees wrote:
>>
.... snip ...
>>
>>> Summary: avoiding goto as a design concept is a Good Thing.
>>> Avoiding gotos as a means of implementing good structure is
>>> simply misunderstanding the point. I've seen (possibly on this
>>> ng) someone defending goto on the basis that CPUs only know
>>> about branches and jumps anyway. Follocks.
>>
>> Not according to me.  Consider the following function outline:
>>
>> int foo( /* whatever */ ) {
>>    int errmk = 0;
>>    FILE *f1, *f2, *fw;
>>
>>    if      (!(f1 = fopen(f1name, "r")) {
>>       errmk = 1; goto f1bad;
>>    }
>>    else if (!(f2 = fopen(f2name, "r")) {
>>       errmk = 2; goto f2bad;
>>    }
>>    else if (!(fw = fopen(fwname, "w")) {
>>       errmk = 3;  goto fwbad;
>>    }
>>    else {
>>       /* files open, play appropriate games */
>>    }
>>    fputs(fwendln, fw);
>>    fclose(fw);
>> fwbad:
>>    fclose(f2);
>> f2bad:
>>    fclose(f1);
>> f1bad:
>>    return errmk;
>> }
>>
>> There are lots of undetected errors left, that is an outline. 
>> Yes, there are other ways to handle it.
> 
> int foo( /* whatever */ ) {
>    int errmk = 0;
>    FILE *f1, *f2, *fw;
>
>    if       (!(f1 = fopen(f1name, "r")) errmk = 1;
>    else {
>       if    (!(f2 = fopen(f2name, "r")) errmk = 2;
>       else { 
>          if (!(fw = fopen(fwname, "w")) errmk = 3;
>          else {           /* Files open */
>             fputs(fwendln, fw);
>             fclose(fw);
>          };
>          fclose(f2);
>       };
>       fclose(f1);
>    };
>    return errmk;
> }

(I have taken liberties reformatting your quote above.)

Well, I did say mine was an outline.  In practice I would probably
write that the way you did.  I guess I wasn't too clear, but I was
trying to illustrate a clear way of using goto with forward jumps.

I'm lazy and don't use it, but I consider goto clearer than break.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/27/2008 1:52:01 AM
On Fri, 25 Apr 2008 00:33:31 -0400, Robert Adsett wrote:

> Echoing the question.  What do you need them for that's not covered by a
> divide by a power of 2?

I can't speak for the original poster, but for some signal processing 
applications, arithmetic-right-shift as a 'division by power of two' is 
better than an explicit actual division by a power of two *because* of 
the consistent round-to-negative-infinity behaviour.  Round-towards-zero, 
which is the standard for signed integer division in C, produces an 
uneven quantization interval around zero, compared to that between all 
other adjacent integers.  This results in significantly (3dB RMS) more 
noise than properly-rounded ASR, unless you go to the bother of adding a 
negative rounding constant when the number is negative.

Cheers,

-- 
Andrew
0
4/27/2008 4:09:24 AM
On Fri, 25 Apr 2008 18:15:15 -0400, CBFalconer wrote:

> Yes, you are, but no, he's not.  Shifts on negative values are undefined
> behaviour on any system.

Only in C.  They're well defined by the processor architecture manuals of 
all processors that provide them, and that I am aware of.  Probably many 
others besides.  What's more, these behaviours are, in my experience, 
consistent.  Since we're all some-time assembly language programmers here 
in c.a.e, I am not at all surprised that we bridle that expected 
behaviour is not supported by the standard.  I know that it bugs me.

Cheers,

-- 
Andrew
0
4/27/2008 4:15:02 AM
In message <4813D6BF.86BBEF32@yahoo.com>, CBFalconer 
<cbfalconer@yahoo.com> writes
>Chris H wrote:
>> <cbfalconer@yahoo.com> writes
>>> Richard Phillips wrote:
>>>
>>>... snip ...
>>>>
>>>> The problem is there is some misunderstanding here.  MISRA lists
>>>> it's rules as "recommended" and "required" (or something like
>>>> that), which makes it sound like "required" rules MUST be obeyed,
>>>> which doesn't appear to be the case from what I now understand.
>>>
>>> The only 'required' rules are those of the C standard.
>>
>> Absolutely NOT. (Which C standard? )
>
>Since MISRA is organized around C90/95, that standard.

Then you have a complete lack of understanding of the subject and the 
standards.


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/27/2008 9:32:46 AM
CBFalconer wrote:
> David Brown wrote:
>> CBFalconer wrote:
>>> Steve at fivetrees wrote:
>>>
> ... snip ...
>>>> Summary: avoiding goto as a design concept is a Good Thing.
>>>> Avoiding gotos as a means of implementing good structure is
>>>> simply misunderstanding the point. I've seen (possibly on this
>>>> ng) someone defending goto on the basis that CPUs only know
>>>> about branches and jumps anyway. Follocks.
>>> Not according to me.  Consider the following function outline:
>>>
>>> int foo( /* whatever */ ) {
>>>    int errmk = 0;
>>>    FILE *f1, *f2, *fw;
>>>
>>>    if      (!(f1 = fopen(f1name, "r")) {
>>>       errmk = 1; goto f1bad;
>>>    }
>>>    else if (!(f2 = fopen(f2name, "r")) {
>>>       errmk = 2; goto f2bad;
>>>    }
>>>    else if (!(fw = fopen(fwname, "w")) {
>>>       errmk = 3;  goto fwbad;
>>>    }
>>>    else {
>>>       /* files open, play appropriate games */
>>>    }
>>>    fputs(fwendln, fw);
>>>    fclose(fw);
>>> fwbad:
>>>    fclose(f2);
>>> f2bad:
>>>    fclose(f1);
>>> f1bad:
>>>    return errmk;
>>> }
>>>
>>> There are lots of undetected errors left, that is an outline. 
>>> Yes, there are other ways to handle it.
>> int foo( /* whatever */ ) {
>>    int errmk = 0;
>>    FILE *f1, *f2, *fw;
>>
>>    if       (!(f1 = fopen(f1name, "r")) errmk = 1;
>>    else {
>>       if    (!(f2 = fopen(f2name, "r")) errmk = 2;
>>       else { 
>>          if (!(fw = fopen(fwname, "w")) errmk = 3;
>>          else {           /* Files open */
>>             fputs(fwendln, fw);
>>             fclose(fw);
>>          };
>>          fclose(f2);
>>       };
>>       fclose(f1);
>>    };
>>    return errmk;
>> }
> 
> (I have taken liberties reformatting your quote above.)
> 

Liberties indeed - it is rare that I would write a statement of the form 
"if (x) y;" without brackets, and I consider it downright foolish to 
omit the brackets when using "else".  The scope for getting your else's 
out of synchronisation with your if's is just far too great.

> Well, I did say mine was an outline.  In practice I would probably
> write that the way you did.  I guess I wasn't too clear, but I was
> trying to illustrate a clear way of using goto with forward jumps.
> 
> I'm lazy and don't use it, but I consider goto clearer than break.
> 

A forward goto is often a choice for breaking out of nested loops, where 
a break won't work.  Personally, I'd prefer to split the code into a 
separate function (if you have a situation like this, your function is 
probably too long anyway) and use a return from within the loop, but 
that's a matter of choice.
0
david.brown (580)
4/27/2008 10:11:07 AM
Andrew Reilly wrote:
> On Fri, 25 Apr 2008 18:15:15 -0400, CBFalconer wrote:

>> Yes, you are, but no, he's not.  Shifts on negative values are undefined
>> behaviour on any system.

> Only in C.  

Which just so happens to be the subject matter.
0
HBBroeker (925)
4/27/2008 1:27:26 PM
David Brown wrote:
> CBFalconer wrote:
>> David Brown wrote:
>>
.... snip ...
>>
>>> int foo( /* whatever */ ) {
>>>    int errmk = 0;
>>>    FILE *f1, *f2, *fw;
>>>
>>>    if       (!(f1 = fopen(f1name, "r")) errmk = 1;
>>>    else {
>>>       if    (!(f2 = fopen(f2name, "r")) errmk = 2;
>>>       else {
>>>          if (!(fw = fopen(fwname, "w")) errmk = 3;
>>>          else {           /* Files open */
>>>             fputs(fwendln, fw);
>>>             fclose(fw);
>>>          };
>>>          fclose(f2);
>>>       };
>>>       fclose(f1);
>>>    };
>>>    return errmk;
>>> }
>>
>> (I have taken liberties reformatting your quote above.)
> 
> Liberties indeed - it is rare that I would write a statement of
> the form "if (x) y;" without brackets, and I consider it
> downright foolish to omit the brackets when using "else".  The
> scope for getting your else's out of synchronisation with your
> if's is just far too great.

I can smell the exclamation marks after 'indeed'. :-)  However,
look at it again.  Notice that the elses are tightly associated
with the appropriate ifs.  At any point following indentation up
exposes the controlling statement.  I maintain it is hard to
misread the flow.  It is also vertically compact, which I consider
an advantage (and was the primary reason for the reformat).

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/27/2008 3:25:06 PM
>I've never seen one that doesn't do an arithmetic right shift
>on signed value...

I have. Old MPW C did a 16-bit signed shift as unsigned, using some 
special 68K operation. I forget the details. That's when I discovered they 
were undefined.

Isn't integer division of negative dividends allowed to truncate to zero 
or to truncate less. (-1/2 == 0 or ==-1).


-- 
	mac the na�f
0
alexc8 (94)
4/27/2008 6:35:04 PM
Alex Colvin schrieb:
> Isn't integer division of negative dividends allowed to truncate to zero 
> or to truncate less. (-1/2 == 0 or ==-1).

There was an issue with this as well. I remember having worked on a 
MetroWerks compiler in my game-development days that made signed 
divisions different to any other compiler.

Those guys also messed up switches with negative cases and other stuff 
as well though. It seems to me like they had big problems with 
signed/unsigned in general.

Don't know how MetroWerks is today. Back 8 years it was a horrible piece 
of junk.

   Nils
0
4/27/2008 8:11:00 PM
On 2008-04-25, CBFalconer <cbfalconer@yahoo.com> wrote:
>
> Yes, you are, but no, he's not.  Shifts on negative values are
> undefined behaviour on any system.

Don't confuse "undefined by the standard" with "undefined, period".
One of the differences between good tools and merely useful tools
is the quality of the documentation.  Amongst other things, this
includes defining undefined behaviour.  It's worth going through
to make yourself aware of any areas where the compiler works in a
way you don't expect, so you can watch out for those particular
cases when undefined behaviour slips in by mistake.  Of course,
merely reading through that portion increases awareness of undefined
aspects in the first place which can only be a good thing.

I have hazy memories of the release notes for an old SCO compiler
including a note to the effect of "The previous version did this
in the undefined case where ..., the new version does something
else instead", but can't be bothered digging out the manuals to
find an exact reference now.

-- 
Andrew Smallshaw
andrews@sdf.lonestar.org
0
andrews (362)
4/27/2008 9:49:07 PM
Alex Colvin wrote:

> Isn't integer division of negative dividends allowed to truncate to zero 
> or to truncate less. (-1/2 == 0 or ==-1).

It was in C90 and successors.  As of C99, it's required to truncate 
towards zero.  I have serious doubts that was a good idea.
0
HBBroeker (925)
4/27/2008 9:59:58 PM
"CBFalconer" <cbfalconer@yahoo.com> wrote in message 
news:4812862C.82C0DEFE@yahoo.com...
> Steve at fivetrees wrote:
>>
>> Things like jump tables are not lists of gotos - they're a list
>> of (derefenced, if you insist) function pointers.
>>
>> Summary: avoiding goto as a design concept is a Good Thing.
>> Avoiding gotos as a means of implementing good structure is
>> simply misunderstanding the point. I've seen (possibly on this
>> ng) someone defending goto on the basis that CPUs only know
>> about branches and jumps anyway. Follocks.
>
> Not according to me.  Consider the following function outline:
>
> int foo( /* whatever */ ) {
>   int errmk = 0;
>   FILE *f1, *f2, *fw;
>
>   if      (!(f1 = fopen(f1name, "r")) {
>      errmk = 1; goto f1bad;
>   }
>   else if (!(f2 = fopen(f2name, "r")) {
>      errmk = 2; goto f2bad;
>   }
>   else if (!(fw = fopen(fwname, "w")) {
>      errmk = 3;  goto fwbad;
>   }
>   else {
>      /* files open, play appropriate games */
>   }
>   fputs(fwendln, fw);
>   fclose(fw);
> fwbad:
>   fclose(f2);
> f2bad:
>   fclose(f1);
> f1bad:
>   return errmk;
> }
>
> There are lots of undetected errors left, that is an outline.  Yes,
> there are other ways to handle it.

Ooh. That's truly horrible - but the underlying logic isn't, it's just coded 
horribly.

I'd probably write that as:

int foo( /* whatever */ )
{
    int errmk = 0;
    FILE *f1, *f2, *fw;
    BOOL f1_open = FALSE, f2_open = FALSE, fw_open = FALSE;

    if ( errmk == 0 )
    {
        if ( !( f1 = fopen( f1name, "r" ))
            errmk = 1;
        else
            f1_open = TRUE;
    }

    if ( errmk == 0 )
    {
        if ( !( f2 = fopen( f2name, "r" ))
            errmk = 2;
        else
            f2_open = TRUE;
    }

    if ( errmk == 0 )
    {
        if ( !(fw = fopen( fwname, "w" ))
            errmk = 3;
        else
            fw_open = TRUE;
    }

    if ( errmk == 0 )
    {
        /* files open, play appropriate games */
        fputs( fwendln, fw );
    }

    if ( fw_open )
        fclose( fw );
    if ( f2_open )
        fclose( f2 );
    if ( f1_open )
        fclose( f1 );
    return( errmk );
}

Note that I've defended myself from code changes - I can move things around, 
and the initial tests and the final closures are independent of any such 
changes.

Note also that I just can't be doing with this opening-brace-on-end-of-line 
heresy: braces should visually line up, and that's the end of it ;).

YMMV ;).

Steve 


0
steve4412 (879)
4/27/2008 11:42:27 PM
"Richard Phillips" <raphillips@ntlworld.com> wrote in message 
news:gIDQj.112578$5i5.4642@newsfe6-gui.ntli.net...
> Steve at fivetrees wrote:
>>
>> Avoiding "goto" means avoiding unstructured design (i.e. using only
>> only closed structures - one start, one end, any other context
>> signalled by other means than programme flow).
>
> Sorry, I think that's just wrong.  If K+R think it's ok and include it in 
> the language, I think there must be some point to it.
> The one case I've encountered where it's "needed" is deeply nested 
> conditional code.  Often encoutered in communications, where you need to 
> test lots of conditions before a packet of data is "accepted".  If the 
> data is rejected at the final check, goto gets you right back out 
> gracefully without lots of extra checking code.

There are plenty of ways of doing exactly this without using gotos (e.g. 
state machines). I've not used a goto in nearly 30 years, and I pride myself 
on clean, readable code. I do a lot of comms, so I know whereof you speak - 
but I think you're missing a load of tricks (e.g. separate validation from 
use - decompose).

Again: it's about the logic, not necessarily the implementation.

Steve 


0
steve4412 (879)
4/28/2008 12:23:23 AM
"Chris H" <chris@phaedsys.org> wrote in message 
news:IuwkdBEGJtEIFA4t@phaedsys.demon.co.uk...
> In message <SuCdnb4TBovD9I_VnZ2dnUVZ8uadnZ2d@pipex.net>, Steve at 
> fivetrees <steve@NOSPAMTAfivetrees.com> writes
>>"Richard Phillips" <raphillips@ntlworld.com> wrote in message
>>news:kukQj.59491$h65.48326@newsfe2-gui.ntli.net...
>>> * You're not supposed to use "goto".  Avoiding this when you're
>>> learning to write code is good practise, but it's very useful in a
>>> limited set of circumstances, if used properly.  I remember a manager
>>> of mine telling a work colleague once that using "goto" was bad
>>> practise, I then showed my colleague my copy of K+R which basically
>>> put him right.
>>>
>>> * You're not supposed to exit from a controlled loop prematurely.
>>
>>Avoiding "goto" means avoiding unstructured design (i.e. using only only
>>closed structures - one start, one end, any other context signalled by
>>other means than programme flow).
>
> However as with all things there are a few exceptions where got is the 
> cleanest solution.  In those cases you need to deviate and be able to 
> stand up in court in 3 years time with your deviation.

Sorry, but I disagree. There are always - ALWAYS - logically-equivalent 
structured alternatives to goto, which will not bite your ass anywhere near 
as badly.

> Intestinally the "goto" is bad" came from a paper by Dykstra  (not Wilco 
> :-) and AFAIK no one has really challenged it but just taken it as read. I 
> know some people are doing some work into it to see if it really is that 
> bad.

Ignoring the "intestinally": you're kidding!

I've said this elsewhere, but the acid test is: if you can't look at a 
section of code and know how you got there, WARNING. Therein is the danger 
of goto. You say that people are seriously questioning this? FFS... are they 
questioning synchronous logic design too?

> I suspect the trouble will be that 90% of those who want to use goto are 
> the sort of people who will write appalling code anyway and 90% of those 
> who think goto should be banned would only ever use it very sensibly.

Agreed.

> So it is a self fore filling prophesy:

Ah - you mean a self-fulfilling prophecy.

No. 2 or 3 years back I had to review the code of a certain engineer who was 
not subject to normal peer review on the basis of his, errr, "adherence to 
open-source methods". Turned out this was a smokescreen. His main() was over 
2000 lines long, and was peppered with gotos. Summary - he was a crap coder. 
I see this a lot - crap coders are crap coders, period. There are good 
reasons for objecting to goto - Dijkstra was no fool. Those who use goto 
simply don't understand the subject very well.

Steve
(ducking and running) 


0
steve4412 (879)
4/28/2008 12:36:27 AM
Steve at fivetrees wrote:
> "Chris H" <chris@phaedsys.org> wrote:
>
.... snip ...
>
>> However as with all things there are a few exceptions where got
>> is the cleanest solution.  In those cases you need to deviate and
>> be able to stand up in court in 3 years time with your deviation.
> 
> Sorry, but I disagree. There are always - ALWAYS - logically-
> equivalent structured alternatives to goto, which will not bite
> your ass anywhere near as badly.

Those equivalents are not free.  General implementation requires
the addition of flag variables.  This was proven about 50 years
ago.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
4/28/2008 2:40:47 AM
In message <HJWdncqgGLWTgYjVnZ2dneKdnZydnZ2d@pipex.net>, Steve at 
fivetrees <steve@NOSPAMTAfivetrees.com> writes
>"Chris H" <chris@phaedsys.org> wrote in message
>news:IuwkdBEGJtEIFA4t@phaedsys.demon.co.uk...
>> However as with all things there are a few exceptions where got is the
>> cleanest solution.  In those cases you need to deviate and be able to
>> stand up in court in 3 years time with your deviation.
>
>Sorry, but I disagree. There are always - ALWAYS - logically-equivalent
>structured alternatives to goto, which will not bite your ass anywhere near
>as badly.

Not so. There are no absolutes. There are occasions when the goto is 
useful. Not often which is why MISRA-C bans goto. It you think you have 
one of the few odd places where it is needed then deviate.


>> Intestinally the "goto" is bad" came from a paper by Dykstra  (not Wilco
>> :-) and AFAIK no one has really challenged it but just taken it as read. I
>> know some people are doing some work into it to see if it really is that
>> bad.
>
>Ignoring the "intestinally": you're kidding!
>
>I've said this elsewhere, but the acid test is: if you can't look at a
>section of code and know how you got there, WARNING. Therein is the danger
>of goto. You say that people are seriously questioning this?

Yes. And these people spend their lives doing code analysis and looking 
at errors. The problem is "everybody knows" goto is bad... no one has 
actually shown any solid evidence that it is. Anecdotal yes but 
mathematical, statistical etc evidence: no.

I have seen some discussions by Les Hatton on this.

>No. 2 or 3 years back I had to review the code of a certain engineer who was
>not subject to normal peer review on the basis of his, errr, "adherence to
>open-source methods". Turned out this was a smokescreen. His main() was over
>2000 lines long, and was peppered with gotos. Summary - he was a crap coder.
>I see this a lot - crap coders are crap coders, period.

I couldn't agree more (but please don't mention "open-source" it gets 
the religious nutters going)

>There are good
>reasons for objecting to goto - Dijkstra was no fool. Those who use goto
>simply don't understand the subject very well.

Actually those who are saying there is no proof that goto is bad 
understand more than you and I put together. They spend their lives on 
this sort of thing.

Whilst everyone has (should have) a gut feeling that go to is bad there 
is no empirical evidence as there is for other things.  I would be 
delighted if you could provide some.  Your anecdote above is just that. 
Not solid evidence.

Goto CAN be used safely. However those who would use it safely tend not 
to use it at all. Those who do use it do not use it well.


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/28/2008 6:34:12 AM
In message <4815392F.5A73CD1E@yahoo.com>, CBFalconer 
<cbfalconer@yahoo.com> writes
>Steve at fivetrees wrote:
>> "Chris H" <chris@phaedsys.org> wrote:
>>
>... snip ...
>>
>>> However as with all things there are a few exceptions where got
>>> is the cleanest solution.  In those cases you need to deviate and
>>> be able to stand up in court in 3 years time with your deviation.
>>
>> Sorry, but I disagree. There are always - ALWAYS - logically-
>> equivalent structured alternatives to goto, which will not bite
>> your ass anywhere near as badly.
>
>Those equivalents are not free.  General implementation requires
>the addition of flag variables.  This was proven about 50 years
>ago.

That was not the problem.  In some cases to remove a goto the resulting 
structure is horribly convoluted and unreadable. It was readability and 
elegance of design. However these situations are few and far between

-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/28/2008 6:35:51 AM
Chris H wrote:

> Whilst everyone has (should have) a gut feeling that go to is bad there
> is no empirical evidence as there is for other things.  I would be
> delighted if you could provide some.  Your anecdote above is just that.
> Not solid evidence.

The structured programming revolution of the '70s has cleaned up to the
point that few people have seen goto-based code.  For proof by personal
revelation, check

http://ftp.stratus.com/vos/multics/pg/moo.pl1

It's actually a good program for its day, pre Boehm and Jacopini.  Trying to
make a change, finding a certain place to put new code, is surprisingly
hard -- not impossible, of course.

Donald Knuth's vindication of some goto statements is at

http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf

        Mel.

0
mwilson (600)
4/28/2008 2:12:55 PM
"CBFalconer" <cbfalconer@yahoo.com> wrote in message 
news:4815392F.5A73CD1E@yahoo.com...
> Steve at fivetrees wrote:
>> "Chris H" <chris@phaedsys.org> wrote:
>>
> ... snip ...
>>
>>> However as with all things there are a few exceptions where got
>>> is the cleanest solution.  In those cases you need to deviate and
>>> be able to stand up in court in 3 years time with your deviation.
>>
>> Sorry, but I disagree. There are always - ALWAYS - logically-
>> equivalent structured alternatives to goto, which will not bite
>> your ass anywhere near as badly.
>
> Those equivalents are not free.  General implementation requires
> the addition of flag variables.  This was proven about 50 years
> ago.

Absolutely. And it's a small price to pay. Given a choice between goto and a 
flag (or state) variable or two, guess which one I'd choose ;). Not because 
of religion, but because of clarity.

Steve


0
steve4412 (879)
4/28/2008 7:37:57 PM
On 26 Apr, 07:57, Chris H <ch...@phaedsys.org> wrote:

> Intestinally the "goto" is bad" came from a paper by Dykstra  (not Wilco
> :-) and AFAIK no one has really challenged it but just taken it as read.

See Donald Knuth (1974). "Structured Programming with Goto
Statements". Computing Surveys 6 (4): 261=96301.
(e.g., http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf)
Also available in "Literate Programming" (ISBN 0-937073-80-6).

stephen
0
4/29/2008 6:03:37 AM
In message 
<f0c87e4b-e426-4043-bce7-2de20250092d@b1g2000hsg.googlegroups.com>, 
stephen <stephenbennyhat@gmail.com> writes
>On 26 Apr, 07:57, Chris H <ch...@phaedsys.org> wrote:
>
>> Intestinally the "goto" is bad" came from a paper by Dykstra  (not Wilco
>> :-) and AFAIK no one has really challenged it but just taken it as read.
>
>See Donald Knuth (1974). "Structured Programming with Goto
>Statements". Computing Surveys 6 (4): 261–301.
>(e.g., http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf)
>Also available in "Literate Programming" (ISBN 0-937073-80-6).

Many thanks.  I will raise this at the next MISRA-C meeting.


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
4/29/2008 6:29:27 AM
Folks,

I always face the "goto would be nice and neat here" problem in all my 
library initialization routines.

It's somewhat identical to the "file open" thing CBFalconer postet 
elsewhere, except that I don't just open 4 files. I initialize several 
sub-systems and all sub-system build up onto each other. So subsystem N 
must never be initialized unless subystem N-1 succeded.


I think we've all have written this kind of code.



My what I *would* like to write for such a  "master library-init 
functions" would be:

int init_the_big_library_lebowsky (foo *bar)
{
   if (!init (sub_system1(bar)) goto failed1;
   if (!init (sub_system2(bar)) goto failed2;
   if (!init (sub_system3(bar)) goto failed3;
   if (!init (sub_system4(bar)) goto failed4;
   if (!init (sub_system5(bar)) goto failed5;
   if (!init (sub_system6(bar)) goto failee6;
   if (!init (sub_system7(bar)) goto failed7;
   if (!init (sub_system8(bar)) goto failed8;

   // we did it!
   return (E_SUCCESS_CODE);

   failed8: { de_init_subsys7(); return ("E_FUCKUP7\n"); }
   failed7: { de_init_subsys6(); return ("E_FUCKUP6\n"); }
   failed6: { de_init_subsys5(); return ("E_FUCKUP5\n"); }
   failed5: { de_init_subsys4(); return ("E_FUCKUP4\n"); }
   failed4: { de_init_subsys3(); return ("E_FUCKUP3\n"); }
   failed3: { de_init_subsys2(); return ("E_FUCKUP2\n"); }
   failed2: { de_init_subsys1(); return ("E_FUCKUP1\n"); }
   failed1: { return ("E_FUCKUP�\n"); }
}


Yes, you counted right: 8 gotos. But the program flow is as easy as it 
could be.

Compare this to a 8 level deep nested tree with " '{'-char must match 
the same line"-rule obeyed, and the "must not put more than 4 levels of 
nesting within a function-rule obeyed as well.

My innocent "initialize the big-library"-function has to be splitted 
into at least two functions and will be expanded to roughly 100 lines of 
dada-code.

The orignal - also it uses goto - is much easier to understand.

Will the MISRA-conformant function become more understandable? I don't 
think so.

For init-orgies like this goto's are a god-sent.

Nils
0
4/29/2008 8:57:26 PM

Nils wrote:

> Folks,
>
> I always face the "goto would be nice and neat here" problem in all my
> library initialization routines.
>
> It's somewhat identical to the "file open" thing CBFalconer postet
> elsewhere, except that I don't just open 4 files. I initialize several
> sub-systems and all sub-system build up onto each other. So subsystem N
> must never be initialized unless subystem N-1 succeded.
>
> I think we've all have written this kind of code.
>
> My what I *would* like to write for such a  "master library-init
> functions" would be:
>
> int init_the_big_library_lebowsky (foo *bar)
> {
>    if (!init (sub_system1(bar)) goto failed1;
>    if (!init (sub_system2(bar)) goto failed2;
>    if (!init (sub_system3(bar)) goto failed3;
>    if (!init (sub_system4(bar)) goto failed4;
>    if (!init (sub_system5(bar)) goto failed5;
>    if (!init (sub_system6(bar)) goto failee6;
>    if (!init (sub_system7(bar)) goto failed7;
>    if (!init (sub_system8(bar)) goto failed8;
>
>    // we did it!
>    return (E_SUCCESS_CODE);
>
>    failed8: { de_init_subsys7(); return ("E_FUCKUP7\n"); }
>    failed7: { de_init_subsys6(); return ("E_FUCKUP6\n"); }
>    failed6: { de_init_subsys5(); return ("E_FUCKUP5\n"); }
>    failed5: { de_init_subsys4(); return ("E_FUCKUP4\n"); }
>    failed4: { de_init_subsys3(); return ("E_FUCKUP3\n"); }
>    failed3: { de_init_subsys2(); return ("E_FUCKUP2\n"); }
>    failed2: { de_init_subsys1(); return ("E_FUCKUP1\n"); }
>    failed1: { return ("E_FUCKUP�\n"); }
> }
>
> Yes, you counted right: 8 gotos. But the program flow is as easy as it
> could be.
>
> Compare this to a 8 level deep nested tree with " '{'-char must match
> the same line"-rule obeyed, and the "must not put more than 4 levels of
> nesting within a function-rule obeyed as well.
>
> My innocent "initialize the big-library"-function has to be splitted
> into at least two functions and will be expanded to roughly 100 lines of
> dada-code.
>
> The orignal - also it uses goto - is much easier to understand.
>
> Will the MISRA-conformant function become more understandable? I don't
> think so.
>
> For init-orgies like this goto's are a god-sent.
>
> Nils

I probably missed something. I am not sure why this
doesn't also solve the problem and gets rid of the goto's.
The generated code size would be very similar.


int init_the_big_library_lebowsky (foo *bar)
{
   if (!init (sub_system1(bar)) { return ("E_FUCKUP�\n"); }
   if (!init (sub_system2(bar)) { de_init_subsys1(); return ("E_FUCKUP1\n"); }
   if (!init (sub_system3(bar)) { de_init_subsys2(); return ("E_FUCKUP2\n"); }
   if (!init (sub_system4(bar)) { de_init_subsys3(); return ("E_FUCKUP3\n"); }
   if (!init (sub_system5(bar)) { de_init_subsys4(); return ("E_FUCKUP4\n"); }
   if (!init (sub_system6(bar)) { de_init_subsys5(); return ("E_FUCKUP5\n"); }
   if (!init (sub_system7(bar)) { de_init_subsys6(); return ("E_FUCKUP6\n"); }
   if (!init (sub_system8(bar)) { de_init_subsys7(); return ("E_FUCKUP7\n"); }

   // we did it!
   return (E_SUCCESS_CODE);
}

w..

0
walter20 (887)
4/29/2008 9:39:01 PM
On 29 Apr, 21:57, Nils <n.pipenbri...@cubic.org> wrote:

> int init_the_big_library_lebowsky (foo *bar)
> {
>    if (!init (sub_system1(bar)) goto failed1;
>    if (!init (sub_system2(bar)) goto failed2;
>    if (!init (sub_system3(bar)) goto failed3;
>    if (!init (sub_system4(bar)) goto failed4;
>    if (!init (sub_system5(bar)) goto failed5;
>    if (!init (sub_system6(bar)) goto failee6;
>    if (!init (sub_system7(bar)) goto failed7;
>    if (!init (sub_system8(bar)) goto failed8;
>
>    // we did it!
>    return (E_SUCCESS_CODE);
>
>    failed8: { de_init_subsys7(); return ("E_FUCKUP7\n"); }
>    failed7: { de_init_subsys6(); return ("E_FUCKUP6\n"); }
>    failed6: { de_init_subsys5(); return ("E_FUCKUP5\n"); }
>    failed5: { de_init_subsys4(); return ("E_FUCKUP4\n"); }
>    failed4: { de_init_subsys3(); return ("E_FUCKUP3\n"); }
>    failed3: { de_init_subsys2(); return ("E_FUCKUP2\n"); }
>    failed2: { de_init_subsys1(); return ("E_FUCKUP1\n"); }
>    failed1: { return ("E_FUCKUP=DF\n"); }

Isn't the point that you "de-init" everything you init, so the returns
after the failed cases are wrong?

It seems to me that you could benefit from some structure here:

int
init_the_big_library_lebowsky (foo *bar)
{
    static const struct
    {
         int (*init)(foo*);
         void (*de_init)(void);
    }
    sys[] =3D
    {
        {init_sub_system0, de_init_subsys0,},
        {init_sub_system1, de_init_subsys1,},
       /* ... */
    };
    int i;

    for (i =3D 0; i < NELEMS(sys); i++)
    {
        if (! (*sys[i].init)(bar))
        {
             // walk back "de-initialising" everything.
             while (--i >=3D 0)
             {
                 (*sys[i].de_init)();
             }
            return E_ERR;
        }
    }

   return E_OK;
}

I wouldn't quite adopt that style in production code, but I stand by
the idea.  The code
only needs to be made right once and adding a new "sub system" is
trivial.

(I neither tested it, nor proved it correct.)
stephen
0
4/29/2008 10:13:53 PM
"CBFalconer" <cbfalconer@yahoo.com> wrote in message news:4811D3BC.EC3B4E67@yahoo.com...
> Wilco Dijkstra wrote:
>> "David Brown" <david@westcontrol.removethisbit.com> wrote:
>>
> ... snip ...
>>
>>> Is the rounding of shifts like this well defined in C?  I can't
>>> remember the exact rules off-hand - perhaps that's why MISRA
>>> doesn't like right shifts of signed integers!
>>
>> No it's not well defined, just like most other things in C, but
>> who cares anyway?!?
>>
>> Compiler writers agree on most of these things, so in reality
>> these things are extremely well defined. Basically nobody cares
>> about what the C standard says exactly as long as their code
>> compiles. If it doesn't work on a particular compiler, it is
>> that compiler's fault. I know, I have dealt with angry customers
>> with millions of lines of code that didn't compile on our
>> expensive but strict ANSI C compiler...
>
> You need copies of the C standard to hand out.  Most of those
> problems have been discussed here, so you have a good selection of
> immediate answers and suggestions available.

Basically if some application works fine when compiled by various compilers
but not if compiler X is used, then it is compiler X that is wrong, not the source
code. The C standard is not relevant if this kind of issue comes up, so handing
out copies of the standard doesn't help (it might be seen as an insult by paying
customers - they pay you to solve their problem, not to be told to rewrite their
code).

The huge amount of existing source code defines the standard that compilers
must adhere to, not the official C standard. It may not be ideal, but that is the
way things are. I would like to see most implementation defined behaviours
explicitly defined (as compilers agree on them anyway), various undefined
behaviours defined and many common compiler extensions standardized.
It seems unlikely the C/C++ committees will ever do the right thing...

>>> Would this be more correct?
>>>
>>> return ~((int) (((unsigned int) (~value)) >> shift);
>>>
>>> I haven't checked it - in particular, corner cases must be
>>> checked.  I'm just spouting ideas for the OP.
>>
>> That's right indeed (replacing the first return above). Of course
>> this still gives you correct behaviour only on 2-complement's
>> CPUs. So it adds a lot of overhead and bugs (given only the OP
>> got it right first time) for no gain whatsoever...
>
> It's still fundamentally wrong - you can't guarantee unsigned to
> signed casts, because an overflow may occur, and the result is
> implementation defined behaviour.

You're quite right that all this does is replacing one kind of implementation
defined behaviour with another - however any piece of non-trivial code relies
on implementation defined behaviour given the C standard is so badly defined.

As I've explained before, you can rely on most implementation defined behaviours
to be implemented identically on the vast majority compilers. So the whole exercise
is pointless as signed shifts work correctly in the first place.

Wilco 


0
5/1/2008 12:28:38 PM
In message <WHiSj.65882$h65.55052@newsfe2-gui.ntli.net>, Wilco Dijkstra 
<Wilco_dot_Dijkstra@ntlworld.com> writes
>
>"CBFalconer" <cbfalconer@yahoo.com> wrote in message 
>news:4811D3BC.EC3B4E67@yahoo.com...
>> Wilco Dijkstra wrote:
>>> "David Brown" <david@westcontrol.removethisbit.com> wrote:
>>>
>> ... snip ...
>>>
>>>> Is the rounding of shifts like this well defined in C?  I can't
>>>> remember the exact rules off-hand - perhaps that's why MISRA
>>>> doesn't like right shifts of signed integers!
>>>
>>> No it's not well defined, just like most other things in C, but
>>> who cares anyway?!?
>>>
>>> Compiler writers agree on most of these things, so in reality
>>> these things are extremely well defined. Basically nobody cares
>>> about what the C standard says exactly as long as their code
>>> compiles. If it doesn't work on a particular compiler, it is
>>> that compiler's fault. I know, I have dealt with angry customers
>>> with millions of lines of code that didn't compile on our
>>> expensive but strict ANSI C compiler...
>>
>> You need copies of the C standard to hand out.  Most of those
>> problems have been discussed here, so you have a good selection of
>> immediate answers and suggestions available.
>
>Basically if some application works fine when compiled by various compilers
>but not if compiler X is used, then it is compiler X that is wrong, not 
>the source
>code.

Commercially this is true.

>The C standard is not relevant if this kind of issue comes up,

I agree. Basic is a good example of this. The world revolves around VB 
not ISO BASIC

>so handing
>out copies of the standard doesn't help (it might be seen as an insult 
>by paying
>customers -

Absolutely. You have to work with the tools available. Standard C is not 
"required" anywhere which is the problem.  If it was legally required to 
have ISO-C compliant compilers then it would be a different matter.

>they pay you to solve their problem, not to be told to rewrite their
>code).
Rewrite their code to a theoretical standard that is not implemented by 
the compilers.

>The huge amount of existing source code defines the standard that compilers
>must adhere to, not the official C standard. It may not be ideal, but 
>that is the
>way things are.

I agree. The standard should be regularising what we have not going off 
at a tangent.


>I would like to see most implementation defined behaviours
>explicitly defined (as compilers agree on them anyway), various undefined
>behaviours defined and many common compiler extensions standardized.
>It seems unlikely the C/C++ committees will ever do the right thing...

I agree... though there is a light at the end of the tunnel as 10 years 
on virtually no one has implemented C99.  However as there are a lot of 
moves to be MISRA-C:2004 compliant the C panels have started to realise 
that unless they come back to the mainstream ISO-C will become as 
irrelevant as ISO BASIC. .


-- 
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England     /\/\/\/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/



0
chris32 (3361)
5/1/2008 1:40:12 PM
Wilco Dijkstra wrote:
> "CBFalconer" <cbfalconer@yahoo.com> wrote:
>> Wilco Dijkstra wrote:
>>
.... snip stuff on arithmetic shifts ...
>>
>>> Compiler writers agree on most of these things, so in reality
>>> these things are extremely well defined. Basically nobody cares
>>> about what the C standard says exactly as long as their code
>>> compiles. If it doesn't work on a particular compiler, it is
>>> that compiler's fault. I know, I have dealt with angry customers
>>> with millions of lines of code that didn't compile on our
>>> expensive but strict ANSI C compiler...
>>
>> You need copies of the C standard to hand out.  Most of those
>> problems have been discussed here, so you have a good selection
>> of immediate answers and suggestions available.
> 
> Basically if some application works fine when compiled by various
> compilers but not if compiler X is used, then it is compiler X
> that is wrong, not the source code. The C standard is not relevant
> if this kind of issue comes up, so handing out copies of the
> standard doesn't help (it might be seen as an insult by paying
> customers - they pay you to solve their problem, not to be told to
> rewrite their code).
> 
> The huge amount of existing source code defines the standard that
> compilers must adhere to, not the official C standard. It may not
> be ideal, but that is the way things are. I would like to see most
> implementation defined behaviours explicitly defined (as compilers
> agree on them anyway), various undefined behaviours defined and
> many common compiler extensions standardized. It seems unlikely the
> C/C++ committees will ever do the right thing...

If you have to build something to run on some users equipment and
compiled on his compilers, that is one thing.  Usually you have the
choice of tools.  Today most C systems make valiant efforts to be
standard compatible, usually to C95, and document their failures. 
Some of those failures are due to the hardware proper.

I can see no reason to shift signed variables, when unsigned is
available.  Every piece of code you write that adheres to the
standard is that much more portable, and won't need rewriting for
another application.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


** Posted from http://www.teranews.com **
0
cbfalconer (19194)
5/1/2008 6:52:15 PM
Reply: