Pascal/C II
 Volume Number: 10 Issue Number: 1 Column Tag: Pascal/C workshop

# The Pascal Programmer’s Guide To Understanding ‘C’

## Teach yourself to read another language - Part II

By Ken Gladstone, MacTech Magazine Technical Editor

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

This article is the second half of my Pascal Programmer’s Guide to Understanding “C”. If you haven’t already, I suggest you read the first half, which appeared in our December 1993 issue - otherwise you will probably be thoroughly confused by this half! That first half covered the following “C” concepts: comments, identifiers, operators, constants, program structure, and variable declarations and scope. So, let’s continue

## PARAMETER PASSING

One key difference between C and Pascal is that C always passes parameters by value, never by reference. Therefore, you may be wondering how a C function can ever modify a passed in parameter. It can’t - but you can accomplish the same thing by passing a pointer to the value you wish to modify, and having the function modify the pointed to value. Here is an example:

```/* 1 */
/************************ C Version *************************/

void doubleIt( int * pointerToIntParam )
{
(*pointerToIntParam) *= 2;
}

int main()
{
int myInt = 3;

doubleIt( & myInt );

return myInt;
}

/******************** End of C Version **********************/

(********************* Pascal Version ***********************)
program myProgram;
var
myInt: INTEGER;

procedure doubleIt( var IntParam: INTEGER );
BEGIN
IntParam := IntParam * 2
END;

BEGIN
myInt := 3;

doubleIt( myInt )
END.

(****************** End of Pascal Version *******************)
```

## OLD VERSUS NEW FUNCTION DECLARATIONS

So far, I’ve been showing functions as follows:

```int MyFunc( int a, char b, float c )
{
/* Code goes here */
}

```

This way of writing functions is an ANSI extension that allows C to perform parameter type checking when calling a function. Things weren’t always so nice. In the original K&R C, functions were written as follows:

```int MyFunc( a, b, c )
int a;
char b;
float c;
{
/* Code goes here */
}

```

In original C compilers, when calling a function, there was no checking of parameter types, or often even of the number of parameters! In old C, you could write a call to a function before it had ever been defined, declared or mentioned in any way! Now, C compilers have much stronger type-checking. For example, Think C has a compiler option to require you to write a function prototype for every function.

## FLOW CONTROL

So far, all of the examples that I’ve shown execute code sequentially - in fact, I’ve only shown declarations, assignment statements, function calls, and function return statements. Like Pascal, C has various loops and other constructs to control the flow of code. We’ll start with the while loop. The while loop in C is nearly identical to the one in Pascal, except that it needs parens around the test expression and it doesn’t have a DO keyword. Examples:

```/* 2 */

while ( i < j ) i *= 2;   // First C example

while i < j DO i := i * 2;  {Pascal Equiv.}

while ( i < j )  // C example w/compound statement
{
sysBeep( 1 );
i *= 2;
}

while i < j DO   {Pascal Equiv.}
BEGIN
sysBeep( 1 );
i := i * 2
END
```

Next we have the C do statement. This is a loop with the test at the end of each iteration, like the Pascal REPEAT statement, but the sense of the while test at the end is the opposite of the Pascal UNTIL test. Unlike the Pascal version, the C version needs braces if the loop contains a compound statement. And again, the while condition needs parens. Example:

```/* 3 */

do // C version
{
sysBeep( x );
++ x;
}
while ( x != 10 );

REPEAT  {Pascal equiv.}
sysBeep( x );
x := x + 1
UNTIL x = 10;

Next we have the for loop.  The for loop in C is far more general than the one in Pascal.
It looks like this:

for ( expr1; expr2; expr3 )
statement;
```

What it does is this: expr1 is an initialization that is performed before executing the loop for the first time. expr2 is a test that is performed before each iteration. As long as expr2 evaluates to non-zero, the looping continues. expr3 is a statement that is performed at the end of every iteration. C does not limit loops to simple count up and count down types. Any or all of the three expressions may be omitted, but the semicolons must remain. Any C for loop can be rewritten as follows:

```/* 4 */

expr1;
while( expr2 )
{
statement;
expr3;
}
Example:

for ( i = 10; i != 0; --i ) // C example
DoIt( i );

for ( i = 10; i; --i )    // An equivalent variation
DoIt( i );

i = 10; // Another equivalent variation
while ( i )
{
DoIt( i );// Could use pre or post decrement
-- i;
}

i = 10; // Yet another equivalent variation
while ( i )
DoIt( i-- );   // Must use post decrement

FOR i := 10 DOWNTO 0 DO   {Pascal equivalent}
DoIt( i );
```

The C if statement is very similar to the Pascal version: The else clause is optional, and the statements can be either simple or compound. The only difference is that C needs parens around the expression, it doesn’t use the THEN keyword, and as always, every statement needs a semicolon. Example:

```/* 5 */

if ( condition ) // C
DoOneThing();
else
{
DoAnother();
AndAnother();
}
```

IF condition THEN {Pascal version}

```/* 6 */

DoOneThing
ELSE
BEGIN
DoAnother;
AndAnother
END
```

C has a case statement that is very similar to the Pascal version. An example should suffice:

```/* 7 */

switch ( x )// C version
{
case 1:
case 2:
DoTheOneOrTwoThing();
break;  // Must explicitly leave each case
case 3:
DoTheThreeThing();
AndTheOtherThreeThing();// Purposely fall through
case 7:
DoTheThreeAndSevenThing();
break;
default:
DoTheDefaultThing();
}
```

CASE x OF { Pascal Version }

```/* 8 */

1, 2:  DoTheOneOrTwoThing;
3:
BEGIN
DoTheThreeThing;
AndTheOtherThreeThing;
DoTheThreeAndSevenThing; { In Pascal, we need this twice }
END;
7:
DoTheThreeAndSevenThing; {In Pascal, we need this twice}
OTHERWISE DoTheDefaultThing
END
```

The previous example used the C break keyword. This keyword is like the Pascal Leave statement, and can be used to break out of the innermost while, do, for, or switch. C also has a continue keyword that like the Pascal Cycle statement. It skips to the next iteration of the innermost while, do or for loop.

Finally, C also has the dreaded goto statement (nothing seems to split programmers into warring factions as well as a goto statement does). Unlike in Pascal, you don’t declare labels in C, you just stick ‘em in the code, and they follow the same syntax as other identifiers. Example:

```/* 9 */

{// C
MyLabel:
x := Function();
if ( x == 10 ) goto MyLabel;
}

LABEL 333; { Pascal }
BEGIN
333: x = Function;
IF x=10 THEN GOTO 333
END
```

## LIBRARY FUNCTIONS

Standard C has oodles of library functions, such as malloc() and fread(), that you would use if you were programming on any computer unless you are programming on a Macintosh which you are. So for the most part, you will use calls like NewPtr() and FSRead() instead. You’ll need to look at your C compiler manual if you are interested in the standard C libraries.

## STRINGS

Amazingly enough, standard C doesn’t really provide much built-in language support for strings. There are several standard C library functions that process strings, but no real string type or operators. C handles strings as simple arrays of the char type. In general, you would create a string in one of the following ways:

```{
char myString[100]; // 100 bytes of storage
char Another[] = "LetTheCompilerCountTheSize";
char * ptrToString;

ptrToString = NewPtr( 100 );
}

```

C also has a different way of representing strings than the Pascal way. Instead of having a length byte followed by a number of characters, C starts immediately with characters, and the string is considered to continue until the occurrence of a zero byte. So this declaration:

```char myString[] = "Foo";

```

creates four bytes of storage. It fills the first three with the word "Foo" and puts a zero byte in the fourth. This convention allows strings of arbitrary length.

This string representation doesn’t fit well with Pascal nor with the Mac toolbox, but don’t despair. C only uses this convention in two places: In string constants (like the "Foo" shown above) and in its library functions. The Mac solves the second problem by shunning the C library that is used by the rest of the world, in favor of its own toolbox. And the compilers on the Mac solve the first problem by introducing an ingenious extension, the \p escape sequence. Here is an example:

```char pascalString[] = "\pFoo";

```

This causes the compiler to insert a Pascal-style length byte at the beginning of the string. It still generates a zero-byte at the end, however. So the above declaration would use five bytes: The first byte contains a 3 (for the Pascal length), the next three bytes contain the string, and the final byte contains the C-style zero byte. So pascalString can be used as a Pascal string, and (pascalString+1) or &pascalString[1] can be used as a C string.

## THE PREPROCESSOR

C compilers include a preprocessor step that reads in the source file, expands macros, and then writes back a temporary file that is fed into the actual compiler. Keep in mind that preprocessor commands are purely compile-time, not run-time operations. They are similar to Pascal {\$ } compiler directives. Instead of being embedded within comments, C preprocessor instructions begin with a number sign ‘#’. Here is a (somewhat contrived) code fragment that includes many of the common preprocessor instructions:

```/* 10 */

#include <stdio.h>

#define DEBUG    // Delete this line before shipping program.
#define PI3.14159
#define square(a)( ( a ) * ( a ) )
#define cube(a)  ( ( a ) * square( a ) )
#define max(a,b) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )

#pragma segment mySegment

/*
* This is a strange function which will return either the
* surface area or the volume of a sphere, whichever is
* larger, for a given radius.
*/
{
#ifdef DEBUG
printf( "Hey, we're in the MaxSurfaceOrVolume function" );
#else
printf( "Hey, we're running the non-debug version" );
#endif

#if 0
```

I could have a bunch of lines of code in here, and they

wouldn't ever be executed, or even compiled.

```/* 11 */

#endif

return max( 4 * PI * square( radius ),
4.0/3.0 * PI * cube( radius ) );
}
```

The following table describes the preceding preprocessor statements:

Preprocessor Statement Meaning

#include <stdio.h> Similar to the Pascal {\$I filename} directive. Paste the contents of the included file into here as if they had actually been typed into this file. The angle brackets generally tell the compiler to look for the include file in its list of “system” file folders. Include files are generally named with a .h at the end. They generally consist of things like typedefs, global variable definitions, function prototypes, preprocessor macros, etc. The Mac compilers provide header files that prototype all the toolbox functions so you don’t have to.

#include "myHeader.h" Same as above, but look in the list of “user” file folders instead of system file folders.

#define DEBUG Similar to the Pascal {\$SETC DEBUG = 1} directive. Define the existence of a preprocessor variable. The existence of the variable can be checked later.

#define PI 3.14159 A simple text substitution. Replace all future occurences of PI with 3.14159.

#define square(a) ((a)*(a)) A substitution that takes parameters. Keep in mind that while a macro like this may look like a function call, it is purely text substitution, and therefore incurs none of the overhead of a function call.

#pragma segment mySegment The #pragma feature allows compiler specific instructions that are not actually part of the C language. Each compiler has its own pragmas. They are used for such things as turning optimizations on and off, disabling compiler warnings, or in this case, telling the compiler in what code segment to put this code. They perform many of the same functions as the miscellaneous Pascal {* } directives.

#ifdef DEBUG Similar to {\$IFC } in Pascal. The subsequent statements will only be compiled if the variable is defined.

#else Similar to {\$ELSEC}. The subsequent statements will only be compiled in the “else” case of the preceding #if.

#endif Similar to {\$ENDC}. Ends a preprocessor #if or #ifdef construction.

#if 0 This is a quick way to disable a chunk of code. Change it to #if 1 to re-enable.

## SUMMARY

You should now know enough C to be able to read C code listings. If you would like to get some more practice at seeing the differences between C and Pascal, you may wish to check out Dave Mark’s first few “Getting Started” articles. Dave wrote both a C and Pascal version for all of his programs in the 1992 columns. And while we didn’t print all of the listings in the magazine, we did include them in the source code disks and in our CD-ROM. Beyond that, you’ll probably have to break down a buy a couple of C books.

Million dollar (no, we won’t pay you, even if you have a good answer!) bonus question: K&R say that the term define is used when actually creating storage for a variable, and that the term declare is used when describing the characteristics of a variable (and only possibly creating storage). So why is it that type declarations, which allocate no storage, are spelled typedef (short for type definition) instead of being spelled typedecl? Perhaps this has been discussed somewhere before, but not that I’ve seen. Personally, I like the C keyword, and think that K&R have the define and declare terms backwards throughout their book!

Community Search:
MacTech Search:

djay Pro 1.1 - Transform your Mac into a...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
Vivaldi 1.0.118.19 - Lightweight browser...
Vivaldi browser. In 1994, two programmers started working on a web browser. Our idea was to make a really fast browser, capable of running on limited hardware, keeping in mind that users are... Read more
Stacks 2.6.11 - New way to create pages...
Stacks is a new way to create pages in RapidWeaver. It's a plugin designed to combine drag-and-drop simplicity with the power of fluid layout. Features: Fluid Layout: Stacks lets you build pages... Read more
xScope 4.1.3 - Onscreen graphic measurem...
xScope is powerful set of tools that are ideal for measuring, inspecting, and testing on-screen graphics and layouts. Its tools float above your desktop windows and can be accessed via a toolbar,... Read more
Cyberduck 4.7 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Labels & Addresses 1.7 - Powerful la...
Labels & Addresses is a home and office tool for printing all sorts of labels, envelopes, inventory labels, and price tags. Merge-printing capability makes the program a great tool for holiday... Read more
teleport 1.2.1 - Use one mouse/keyboard...
teleport is a simple utility to let you use one single mouse and keyboard to control several of your Macs. Simply reach the edge of your screen, and your mouse teleports to your other Mac! The... Read more
Apple iMovie 10.0.8 - Edit personal vide...
With an all-new design, Apple iMovie lets you enjoy your videos like never before. Browse your clips more easily, instantly share your favorite moments, and create beautiful HD movies and Hollywood-... Read more
Box Sync 4.0.6233 - Online synchronizati...
Box Sync gives you a hard-drive in the Cloud for online storage. Note: You must first sign up to use Box. What if the files you need are on your laptop -- but you're on the road with your iPhone? No... Read more
Fantastical 2.0.3 - Create calendar even...
Fantastical 2 is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event... Read more

## Latest Forum Discussions

SoundHound + LiveLyrics is Making its De...
SoundHound Inc. has announced that SoundHound + LiveLyrics, will be one of the first third-party apps to hit the Apple Watch. With  SoundHound you'll be able to tap on your watch and have the app recognize the music you are listening to, then have... | Read more »
Adobe Joins the Apple Watch Lineup With...
A whole tidal wave of apps are headed for the Apple Watch, and Adobe has joined in with 3 new ways to enhance your creativity and collaborate with others. The watch apps pair with iPad/iPhone apps to give you total control over your Adobe projects... | Read more »
Z Steel Soldiers, Sequel to Kavcom'...
Kavcom has released Z Steel Soldiers, which continues the story of the comedic RTS originally created by the Bitmap Brothers. [Read more] | Read more »
Seene Lets You Create 3D Images With You...
Seene, by Obvious Engineering, is a 3D capture app that's meant to allow you to create visually stunning 3D images with a tap of your finger, and then share them as a 3D photo, video or gif. [Read more] | Read more »
Lost Within - Tips, Tricks, and Strategi...
Have you just downloaded Lost Within and are you in need of a guiding hand? While it’s not the toughest of games out there you might still want some helpful tips to get you started. [Read more] | Read more »
The Petcube Camera is a device that lets you use live video to check in on your pet, talk to them, and play with them using a laser pointer - all while you're away. And the Petcube app is coming to the Apple Watch, so you'll be able to hang out with... | Read more »
Now You Can Manage Your Line2 Calls With...
You'll be able to get your Line2 cloud phone service on the Apple Watch very soon. The watch app can send and receive messages using hands-free voice dictation, or by selecting from a list of provided responses. [Read more] | Read more »
R.B.I. Baseball 15 (Games)
R.B.I. Baseball 15 1.01 Device: iOS Universal Category: Games Price: \$4.99, Version: 1.01 (iTunes) Description: The legendary Major League Baseball franchise returns to the diamond. Make History. ** ALL iPOD Touch, the iPad 2 and the... | Read more »
Here's How You Can Tell if an App W...
The Apple Watch is pretty much here, and that means a whole lot of compatible apps and games are going to be updated or released onto the App Store. That's okay though, beacause Apple has quietly updated their app description pages to make things... | Read more »
Forgotten Memories : Alternate Realities...
Forgotten Memories : Alternate Realities 1.0.1 Device: iOS Universal Category: Games Price: \$4.99, Version: 1.0.1 (iTunes) Description: + REDUCED PRICE ONLY THE LAUNCHING WEEK + "The most exciting horror game of 2015." - AppSpy... | Read more »

## Price Scanner via MacPrices.net

Intel Compute Stick: A New Mini-Computing For...
The Intel Compute Stick, a new pocket-sized computer based on a quad-core Intel Atom processor running Windows 8.1 with Bing, is available now through Intel Authorized Dealers across much of the... Read more
Heal to Launch First One-Touch House Call Doc...
Santa Monica, California based Heal, a pioneer in on-demand personal health care services — will offer the first one-touch, on-demand house call doctor app for the Apple Watch. Heal’s Watch app,... Read more
Mac Notebooks: Avoiding MagSafe Power Adapter...
Apple Support says proper usage, care, and maintenance of Your Mac notebook’s MagSafe power adapter can substantially increase the the adapter’s service life. Of course, MagSafe itself is an Apple... Read more
12″ Retina MacBook In Shootout With Air And P...
BareFeats’ rob-ART morgan has posted another comparison of the 12″ MacBook with other Mac laptops, noting that the general goodness of all Mac laptops can make which one to purchase a tough decision... Read more
FileMaker Go for iPad and iPhone: Over 1.5 Mi...
FileMaker has announced that its FileMaker Go for iPad and iPhone app has surpassed 1.5 million downloads from the iTunes App Store. The milestone confirms the continued popularity of the FileMaker... Read more
Sale! 13-inch 2.7GHz Retina MacBook Pro for \$...
Best Buy has the new 2015 13″ 2.7GHz/128GB Retina MacBook Pro on sale for \$1099 – \$200 off MSRP. Choose free shipping or free local store pickup (if available). Price for online orders only, in-... Read more
Minimalist MacBook Confirms Death of Steve Jo...
ReadWrite’s Adriana Lee has posted a eulogy for the “Digital Hub” concept Steve Jobs first proposed back in 2001, declaring the new 12-inch MacBook with its single, over-subscribed USB-C port to be... Read more
13-inch 2.7GHz Retina MacBook Pro for \$1234 w...
Adorama has the 13″ 2.7GHz/128GB Retina MacBook Pro in stock for \$1234.99 (\$65 off MSRP) including free shipping plus a free LG external DVD/CD optical drive. Adorama charges sales tax in NY & NJ... Read more
13-inch 2.5GHz MacBook Pro available for \$999...
Adorama has the 13-inch 2.5GHz MacBook Pro on sale for \$999 including free shipping plus NY & NJ sales tax only. Their price is \$100 off MSRP. Read more
Save up to \$600 with Apple refurbished Mac Pr...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to \$600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more

## Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Service-Learning Counselor, *APPLE* Corps -...
…CONTRACT TITLE Higher Education Assistant FLSA Exempt CAMPUS SPECIFIC INFORMATION APPLE Corps (Academic Preparation Program for Law Enforcement), a partnership between Read more
*Apple* iOS Specialist - Kforce (United Stat...
Our client is seeking an Apple iOS Specialist to join their team in Quincy, Massachusetts (MA). Duties: * Responsible for configuration and distribution of desktop, Read more
*Apple* Systems Engineer - Axius Technologie...
* Must be Apple -Certified specialist and will be responsible for all hardware: device settings, images creation/deployment, security implementation * Responsible for all Read more