[comp.lang.pascal] C Ternary Conditional Expression?

cdb@hpclcdb.HP.COM (Carl Burch) (05/24/89)

Can anyone think of a way to express in Pascal a form equivalent to the
ternary conditional expression in C without using a separate statement?
I need to speed up an expression that usually matches a cached value, but 
can't figure out how to move the code out of the called function
( represented by f(indx) below) to save the procedure call overhead.

For instance, how could one translate :

 a[ (indx == last_indx) ? last_val : f(indx) ] = a [ y ];

without using an IF statement?  Preferably without using a temporary variable.

The only Pascal equivalent I've generated is :

 IF (indx = last_indx)
    THEN temp := last_val
    ELSE temp := f(indx);
 a[temp] := a[y];

Please omit all flames - I just happen to know how to do this in C and nobody
I've asked has been able to design a Pascal equivalent.

							Thanks,

							Carl Burch

jwolf@hpcupt1.HP.COM (John Wolf) (05/25/89)

The following pascal statement is a more elegant way of expressing the above 
C statement, one less stack variable is used (i.e. no temporary variable
is required)...

IF (indx = last_indx)
  THEN a[last_val] := a[y] 
  ELSE a[f(indx)] := a[y];

However, the machine code emitted for the C statement mostly matches
the paradigm of Pascal statements you specified:

 IF (indx = last_indx)
    THEN temp := last_val
    ELSE temp := f(indx);
 a[temp] := a[y];

i.e. a temporary variable (or register) is set in the context of a
conditional branch and is later dereferenced as an array index.

John Wolf / x74682 / jwolf@hpda.HP.COM

davidr@hplsla.HP.COM (David M. Reed) (05/26/89)

Just as a side comment (that I probably should not even be making here), but
something I have long wanted to say:

I first learned Pascal, and have recently been learning C.  My first impression
was that, for the most part, C was a "shorthand" version of Pascal (such as 
using '{' for 'BEGIN'), for those who do not know how to type, or do not want 
to type a lot, or are lazy, or have to work only through old, slow teletype
systems.  However, C programmers have continually reminded me how "efficient" 
code can be written in C verses Pascal, such as

    a[ (indx == last_indx) ? last_val : f(indx) ] = a [ y ];

instead of

    IF (indx = last_indx)
       THEN temp := last_val
       ELSE temp := f(indx);
    a[temp] := a[y];

But that only means that you can write source code more concisely, not that
the actual machine code is more concise (depending on the compiler, of course).
Typically I find, as someone else has written:

> ... the machine code emitted for the C statement mostly matches
> the paradigm of Pascal statements you specified...

So why write in the terse C format? I personally think that
   
    loop = loop + 1;

is more clear than

    loop += 1;

or the horrendous

    loop++;

And I despise things like

    y = ++x;

where one has to remember small details (like increment before or after?).
(Working with pointers in C can be a real nightmare because of things like
this.) If written out in the Pascal style (which can be done in C) there would 
not have to be any remembering, for it would be very clear.

The code generated (depending on the compiler) is not any different for the
first three statements, but logically the first is understandable even
to those who know nearly nothing about programming.  (But maybe that, in
part, is why people like to use C.  It is a specialized, hidden language like
the Lawyers use to hide or obscure details from "common" people.)

All the person writing C has done, then, is to write less clear code in
fewer lines, often making it harder to understand and maintain later (even
by the original author, and even if well commented).  

Yes, there are truly occasions where C is a better choice for writing programs,
but personally I believe that is a very small percentage of the time.  Since I 
do not write operating systems, and I feel the code generated by Turbo Pascal 
is outstanding (excepting the occasional place where assembly language needs
to be used, which is true even in C), I use Pascal predominantly.

verwer@ruuinf.cs.ruu.nl (Nico Verwer) (05/26/89)

In article <6490002@hplsla.HP.COM>, davidr@hplsla.HP.COM (David M. Reed) writes:
> However, C programmers have continually reminded me how "efficient" 
> code can be written in C verses Pascal, such as
> 
>     a[ (indx == last_indx) ? last_val : f(indx) ] = a [ y ];
> 
> instead of
> 
>     IF (indx = last_indx)
>        THEN temp := last_val
>        ELSE temp := f(indx);
>     a[temp] := a[y];
> 
> But that only means that you can write source code more concisely, not that
> the actual machine code is more concise (depending on the compiler, of course).
> [...]
> So why write in the terse C format? I personally think that

I think this is one of the few places where C is a "higher-level" language
than Pascal. Of course the compiler will generate code that allocates space
for a temporary variable (temp) in both cases, but why declare this variable
in your program? Personally, I would like to write the above as

      a[ IF index = last_index THEN last_val ELSE f(index) ] := a[ y ] ;

This would extend the IF-statement to conditional expressions, which in my
view is a higher-level construct than the conditional statement in Pascal,
because it allows one to write better readable code.

> All the person writing C has done, then, is to write less clear code in
> fewer lines, often making it harder to understand and maintain later (even
> by the original author, and even if well commented).  

That is why I use Pascal most of the time, that is, if I'm doing
low-level, time/space-efficient coding. When speed/memory is not
important I use prolog or some functional language, of course.

=====================================================================
   /|  /           University of Utrecht, Dept. of Computer Science
  / | /            VOICE: +31-30-533921          || Postbus 80.089
 /  |/ico Verwer   INTERNET: verwer@cs.ruu.nl    || 3508 TB Utrecht
                   UUCP: ...!hp4nl!ruuinf!verwer || the Netherlands
=====================================================================

pgcomp@pbinfo.UUCP (Projektgr. Uebersetzerbau) (05/26/89)

In article <950025@hpclcdb.HP.COM> cdb@hpclcdb (Carl Burch) writes:

>Can anyone think of a way to express in Pascal a form equivalent to the
>ternary conditional expression in C without using a separate statement?
>I need to speed up an expression that usually matches a cached value, but 
>can't figure out how to move the code out of the called function
>( represented by f(indx) below) to save the procedure call overhead.
>
>For instance, how could one translate :
>
> a[ (indx == last_indx) ? last_val : f(indx) ] = a [ y ];
>
>without using an IF statement?  Preferably without using a temporary variable.
>
>The only Pascal equivalent I've generated is :
>
> IF (indx = last_indx)
>    THEN temp := last_val
>    ELSE temp := f(indx);
> a[temp] := a[y];
>
>Please omit all flames - I just happen to know how to do this in C and nobody
>I've asked has been able to design a Pascal equivalent.
>


 Since BOOLEAN Values should be implemented as
   TYPE BOOLEAN = (FALSE,TRUE);
 
 simply try
   a[ord(indx=last_indx)*last_val+ord(indx<>last_indx)*f(indx)] := a[y];
 
 or 
   a[ord(indx=last_indx)*last_val+(1-ord(indx=last_indx))*f(indx)] := a[y];
   
 whichever is faster.

			 thomas roemke

jwolf@hpcupt1.HP.COM (John Wolf) (05/27/89)

I'm not going to get into a discussion of how C or Pascal are
better then each other.  But there are attributes of C which
lend to generation of "more efficient code" (whatever that
means).  To state three: pointer arithmetic, less stingent
type checking and bitwise manipulation.  These attributes 
alone make operating system or low level software development
significantly simpler.  I currently develop low level (O.S.)
software for the hp3000 using a Pascal spinoff.  That is,
the Pascal used is an enhanced Pascal to accomodate the above
stated C attributes among other language shortcomings.
This software engineer and others using Pascal here are 
constantly jumping through hoops and doing contortions
to accomplish what C can do in a single statement.
Here are some other points:

>So why write in the terse C format? I personally think that
>   
>    loop = loop + 1;
On most machines the above statement would generate an Add machine
instrucion...

>is more clear than
>
>    loop += 1;
>
>or the horrendous
>
>    loop++;
when on the same machine a increment machine instruction is generated
for the two above statements which require less CPU cycles then an 
add instruction.
 
>And I despise things like
>
>    y = ++x;
>
>where one has to remember small details (like increment before or after?).
Yes, these can be a tough call.  However, the above C statement doesn't 
require the programmer to know 'x's structure size inorder to increment it,
thanks to C's smart pointer arithmetic.

>(But maybe that, in
>part, is why people like to use C.  It is a specialized, hidden language like
>the Lawyers use to hide or obscure details from "common" people.)
>
This is true, some programmers enjoy writing terse uncomprehensible code
and, there by, cramming two pages of source code into a single page 
using critic C, it's fun.

>All the person writing C has done, then, is to write less clear code in
>fewer lines, often making it harder to understand and maintain later (even
>by the original author, and even if well commented).  
>
If C had interrupt capabilities there would be no need for coding in
assembly.  C provides the flexibility of both creating a high level 
level of abstraction and hugging the paradigm of a given machine -
depending on the skills and preference of the programmer.  For that reason
Programmers eventually leave Pascal behind with the educators for C because 
C's inherent freedom of expression.

Just an opinion, please don't flame
John Wolf / X74682 47UP E6 / jwolf@hpda.HP.COM

jwb@LINDENTHAL.CAE.RI.CMU.EDU (John Baugh) (05/27/89)

In article <1344@ruuinf.cs.ruu.nl> verwer@ruuinf.cs.ruu.nl (Nico Verwer) 
writes:
[stuff deleted]
>in your program? Personally, I would like to write the above as
>
>      a[ IF index = last_index THEN last_val ELSE f(index) ] := a[ y ] ;
>
>This would extend the IF-statement to conditional expressions, which in my
>view is a higher-level construct than the conditional statement in Pascal,
>because it allows one to write better readable code.

I think this (i.e., a preference for one or the other) is a 
philosophical issue.  Some like to separate "statement-like"
phrases from "expression-like" ones, allowing side-effects 
only in statements.  That is, statements are for changing
state, expressions for computing values from states.  This
way of looking at things actually simplifies correctness
arguments, in particular, non-interference specifications.

[stuff deleted]

John Baugh
-- 

milne@ics.uci.edu (Alastair Milne) (05/27/89)

>... Personally, I would like to write the above as
>
>      a[ IF index = last_index THEN last_val ELSE f(index) ] := a[ y ] ;
>
>This would extend the IF-statement to conditional expressions, which in my
>view is a higher-level construct than the conditional statement in Pascal,
>because it allows one to write better readable code.

    Even putting complicated indexing expressions into []'s is enough
    seriously to compromise readability.  Having an entire statement lodged 
    in them seems to me even worse.  The contention that this code is more
    readable seems to me quite unsupported.

    Years ago, ALGOL allowed IF's to return a value, and one could construct
    just this sort of thing.  Wirth, apparently deliberately, left it out of
    Pascal.  Before we start wishing to have it back, let's find out why it
    has been avoided.


    Alastair Milne

art@buengc.BU.EDU (A. R. Thompson) (05/28/89)

In article <15926@paris.ics.uci.edu> Alastair Milne <milne@ics.uci.edu> writes:
>>... Personally, I would like to write the above as
>>
>>      a[ IF index = last_index THEN last_val ELSE f(index) ] := a[ y ] ;
>>
>>This would extend the IF-statement to conditional expressions, which in my
>>view is a higher-level construct than the conditional statement in Pascal,
>>because it allows one to write better readable code.
>
>    Even putting complicated indexing expressions into []'s is enough
>    seriously to compromise readability.  Having an entire statement lodged 
>    in them seems to me even worse.  The contention that this code is more
>    readable seems to me quite unsupported.

But it's not a statement it's an expression.  It just happens to look like
a statement.

>
>    Years ago, ALGOL allowed IF's to return a value, and one could construct
>    just this sort of thing.  Wirth, apparently deliberately, left it out of
>    Pascal.  Before we start wishing to have it back, let's find out why it
>    has been avoided.

If's would not "return" values.  What you are discussing is a thing called
a "conditional expression".  It has the form: "if be then e1 else e2".
Where be must be an expression of type boolean and e1 and e2 must be
expressions of compatible type and the else part must not be empty.  More
generally this extends to a "case" expression.

The conditional expression appeared in SAIL, a re-worked ALGOL from the
Stanford AI lab (SAIL=Stanford Artificial Intelligence Language).  It was
great fun to program in (lotsa dirty tricks).

I don't know why Wirth left them out of Pascal.  Probably in keeping with
the "simple for teaching" philosophy that was at once Pascal's greatest
strength and greatest weakness.  I sorely missed them, but since I've
discovered Lisp I don't feel quite so lonely.  I believe conditional
expressions should indeed be part of the language because they are a
natural thing to do and reflect quite directly the intention of the
programmer.

e.g.
Doesn't i:= if x<0 then 1 else i+x seem to play better than:

   if x<0 then
      i:=1
   else
      i:=i+x ?

It does to me.  Clearly the net effect is identical (codewise too
probably), but the conditional expression says what I mean more directly.

diamond@diamond.csl.sony.junet (Norman Diamond) (05/29/89)

In article <6490002@hplsla.HP.COM> davidr@hplsla.HP.COM (David M. Reed) writes:

>However, C programmers have continually reminded me how "efficient" 
>code can be written in C verses Pascal, such as
>    a[ (indx == last_indx) ? last_val : f(indx) ] = a [ y ];
>instead of
>
>    IF (indx = last_indx)
>       THEN temp := last_val
>       ELSE temp := f(indx);
>    a[temp] := a[y];

Actually the same could be done in Algol.  It is strange that C copied
that construct when no other language has done so.  Anyway it is ugly
and obfuscated.

>So why write in the terse C format? I personally think that
>    loop = loop + 1;
>is more clear than
>    loop += 1;

I don't like the <op>= forms because it's too easy to miss the <op>
when reading, but it really has an advantage when "loop" is really a
big long hairy expression.

>or the horrendous
>    loop++;

This is not so horrendous.  It is not too easy to miss "++".  In fact,
Brinch Hansen and other designers of Pascal dialects included generic
INC and DEC procedure calls to do such operations.

>And I despise things like
>
>    y = ++x;

Now we agree.  This manner of hiding side-effects is also ugly and
obfuscated.

Worst is:

    if (a=b) <some-statement>

This assigns b to a quite legally, and tests that value for non-zero,
but doesn't compare a to b.  Yup, C's philosophy is that programmers
know what they're doing, and that C programmers know every time they've
just made a typo, and that C programmers know they've forgotten every
other programming language they've ever used....

--
Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.co.jp@relay.cs.net)
  The above opinions are my own.   |  Why are programmers criticized for
  If they're also your opinions,   |  re-implementing the wheel, when car
  you're infringing my copyright.  |  manufacturers are praised for it?

gateley@m2.csc.ti.com (John Gateley) (05/30/89)

Just a bit of history about the expression oriented if: Algol was not
the first language to include this. I am not sure what is, but
it is probably Lisp, using cond.

John
gateley@tilde.csc.ti.com

art@buengc.BU.EDU (A. R. Thompson) (06/02/89)

In article <79363@ti-csl.csc.ti.com> gateley@m2.UUCP (John Gateley) writes:
>
>Just a bit of history about the expression oriented if: Algol was not
>the first language to include this. I am not sure what is, but
>it is probably Lisp, using cond.

Actually it's about a dead heat as both languages were being worked on at
the same time.

mcdonald@uxe.cso.uiuc.edu (06/03/89)

<(Subject is the Pascal -C flame war).

I have never really programmed in Pascal; I went from Fortran and
assembler to C. It took me about 5 minutes to learn and understand
the syntax and importance of such C constructs as
    a = x++;

    a += x;

    if( a = y) q = p++;

and so forth: macro expansions and function side effects.

C's pointer declaration syntax is indeed a disaster area, but the
utility is enormous. Virtually anything can be written in straightforward
C, including OS code, device drivers, and interrupt handlers.

The best way to understand the difference between C and PAscal is to realize
that C was designed to implement an entire operating system from the ground
up, and Pascal was designed as a teaching language, essentially a toy.

A so it is today: C is for secure grown-ups, Pascal is for the insecure.

Test for the PAscal lover: translate all of Unix into (legal, ISO
standard, with NO extensions) Pascal.

rang@cpsin3.cps.msu.edu (Anton Rang) (06/04/89)

In article <50600002@uxe.cso.uiuc.edu> mcdonald@uxe.cso.uiuc.edu writes:

   I have never really programmed in Pascal; I went from Fortran and
   assembler to C. It took me about 5 minutes to learn and understand
   the syntax and importance of such C constructs as
       a = x++;

       a += x;

       if( a = y) q = p++;

These don't add any power to the language.  I will agree that they are
shorter than the equivalent Pascal code, though.

   C's pointer declaration syntax is indeed a disaster area, but the
   utility is enormous. Virtually anything can be written in straightforward
   C, including OS code, device drivers, and interrupt handlers.

True enough.  C is basically assembly language dressed up, so you can
work at the bare-bones machine level.  Pascal doesn't let you do this,
at least if you adhere to the ISO standard.  Then again, device
drivers and interrupt handlers are not exactly portable, so it doesn't
hurt any to use your favorite extensions when programming these in
Pascal.
  I've written OS (kernel mode) code using Pascal before, on a VAX.
The code is about 30% shorter in Pascal than its C equivalent (which I
also wrote out for fun, and to give to a friend who didn't have the
Pascal compiler).  The reason is that Pascal has string handling and
variable-length (conformant) arrays built in; since C has the simplest
(most naive) string handling, it's lots more work to interface to
other languages which support string descriptors, for instance.

   The best way to understand the difference between C and PAscal is to realize
   that C was designed to implement an entire operating system from the ground
   up, and Pascal was designed as a teaching language, essentially a toy.

C is glorified assembly language (adding control structures and an
easier method of structure handling).  Pascal is designed to make
programming in it easier, though less flexible unless you use
extensions.  The extensions aren't built in, because they vary a LOT
from machine to machine.  (Just out of curiousity, are there any C
implementations on Lisp machines?  Pascal runs great on a Symbolics,
getting along happily with Lisp and the OS.)

   A[nd] so it is today: C is for secure grown-ups, Pascal is for the insecure.

C is for people who need to write either semi-portable code under
UNIX, or for people who dislike the convolutions needed to do odd
things (like treat a string as a floating-point number, or an integer
as a pointer) in Pascal.
  Pascal is for people who prefer programming in a more structured
manner.  It catches many of the errors which the programmer can make.
(I believe there was a discussion of this on comp.misc--features which
were desirable within a language to aid in debugging.)  It has strong
type checking.  It allows both pass-by-value and pass-by-reference.
It also allows nested procedures; this makes it much easier to control
the visibility of variables, and makes it easier to work on large
projects.  (This is a serious omission in C.)

   Test for the Pascal lover: translate all of Unix into (legal, ISO
   standard, with NO extensions) Pascal.

Well, it would be easier if you'd translate it all into C first.
Seriously, this would be tough.  Then again, if you can translate it
into ANSI C, I can translate it into ISO Pascal.  Why?  Because the
*only* "feature" of C which is "missing" in Pascal is the lack of type
checking.  Pascal allows variant records to handle this.  It would be
longer than the equivalent C, but both languages let you do the same
things--neither one is more powerful than the other.  However, it
requires some NASTY convolutions to translate Pascal with nested
procedures and functions into C.
  I program in both C and Pascal, depending on the system I'm using.
VAXen work much better with Pascal (and have the best implementation
I've used).  I use C on my Mac at the moment, but will be picking up
Pascal this summer and may start using that instead.  On UNIX systems,
I use C (when I can't avoid programming.)

					Anton

+---------------------------+------------------------+
| Anton Rang (grad student) | "VMS Forever!"         |
| Michigan State University | rang@cpswh.cps.msu.edu |
+---------------------------+------------------------+

diamond@diamond.csl.sony.junet (Norman Diamond) (06/05/89)

In article <50600002@uxe.cso.uiuc.edu> mcdonald@uxe.cso.uiuc.edu writes:

><(Subject is the Pascal -C flame war).

>Pascal was designed as a teaching language

True

>essentially a toy.

False, but many implementations were toys.

>A so it is today: C is for secure grown-ups, Pascal is for the insecure.
>Test for the PAscal lover: translate all of Unix into (legal, ISO
>standard, with NO extensions) Pascal.

Well, all of Unix could be translated into the new ISO draft standard
"Extended Pascal" (with no extensions to the standard, with this
unfortunate name).

Test for the C lover:  do the same into ANSI C.

--
Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.co.jp@relay.cs.net)
  The above opinions are my own.   |  Why are programmers criticized for
  If they're also your opinions,   |  re-implementing the wheel, when car
  you're infringing my copyright.  |  manufacturers are praised for it?

dik@cwi.nl (Dik T. Winter) (06/05/89)

In article <79363@ti-csl.csc.ti.com> gateley@m2.UUCP (John Gateley) writes:
 > 
 > Just a bit of history about the expression oriented if: Algol was not
 > the first language to include this. I am not sure what is, but
 > it is probably Lisp, using cond.
 > 
I do not know, but seeing that Algol and Lisp date from around the same
period (1958-1960), this makes Algol still a good candidate.
-- 
dik t. winter, cwi, amsterdam, nederland
INTERNET   : dik@cwi.nl
BITNET/EARN: dik@mcvax

mdfreed@ziebmef.uucp (Mark Freedman) (06/06/89)

(C-bashing ...)
>     Worst is:
>        if (a = b)  <some statement>

   Most MS-DOS compilers issue a warning  (e.g. "possible unintended assignmentt").
    The first time I found a typo because of this sort of warning, I nearly
forgave Datalight for all the other bugs in its C compiler :-)
  
    I suppose that other environments (i.e. UNIX) rely on standalone utilities
such as lint. This may be less convenient.