TweetFollow Us on Twitter

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


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;
    myInt: INTEGER;

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

  myInt := 3;

  doubleIt( myInt )

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


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.


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.}
  sysBeep( 1 );
  i := i * 2

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 )

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 */

while( expr2 )

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

IF condition THEN {Pascal version}

/* 6 */


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:
    break;  // Must explicitly leave each case
  case 3:
    AndTheOtherThreeThing();// Purposely fall through
  case 7:

CASE x OF { Pascal Version }

/* 8 */

  1, 2:  DoTheOneOrTwoThing;
      DoTheThreeAndSevenThing; { In Pascal, we need this twice }
      DoTheThreeAndSevenThing; {In Pascal, we need this twice}
  OTHERWISE DoTheDefaultThing

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
    x := Function();
    if ( x == 10 ) goto MyLabel;

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


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.


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.


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>
#include "myheader.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

double MaxSurfaceOrVolume( double radius )
 * 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" );
  printf( "Hey, we're running the non-debug version" );

#if 0

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

wouldn't ever be executed, or even compiled.

/* 11 */


  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.


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:

Software Updates via MacUpdate

Hopper Disassembler 5.6.1 - Binary disas...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more
Skim 1.6.11 - PDF reader and note-taker...
Skim is a PDF reader and note-taker for OS X. It is designed to help you read and annotate scientific papers in PDF, but is also great for viewing any PDF file. Skim includes many features and has a... Read more
Alfred 4.6.7 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Transmit 5.8.7 - Excellent FTP/SFTP clie...
Transmit is an excellent FTP (file transfer protocol), SFTP, S3 ( file hosting) and iDisk/WebDAV client that allows you to upload, download, and delete files over the internet. With the... Read more
Adobe Lightroom Classic 11.4.1 - Import,...
You can download Lightroom for Mac as a part of Creative Cloud for only $9.99/month with Photoshop, included as part of the photography package. The latest version of Lightroom gives you all of the... Read more
MarsEdit 4.5.9 - Quick and convenient bl...
MarsEdit is a blog editor for OS X that makes editing your blog like writing email, with spell-checking, drafts, multiple windows, and even AppleScript support. It works with with most blog services... Read more
Thunderbird 91.11.0 - Email client from...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more
A Better Finder Rename 11.50 - File, pho...
A Better Finder Rename is the most complete renaming solution available on the market today. That's why, since 1996, tens of thousands of hobbyists, professionals and businesses depend on A Better... Read more
DaisyDisk 4.23 - $9.99
DaisyDisk allows you to visualize your disk usage and free up disk space by quickly finding and deleting big unused files. The program scans your disk and displays its content as a sector diagram... Read more
BBEdit 14.5 - Powerful text and HTML edi...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more

Latest Forum Discussions

See All

Downhill Mountain Biking Game ‘Descender...
Just over three years ago in May of 2019 developer RageSquid and publisher No More Robots released a quirky downhill mountain biking game called Descenders on PC and Xbox One. Bemoaning a lack of “extreme sports" titles in recent years led RageSquid... | Read more »
SwitchArcade Round-Up: ‘Monster Hunter R...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for June 30th, 2022. Thursday is once more upon us, and that means a bunch of new releases to look at. We start things off with DLC for some very big games, Monster Hunter Rise and... | Read more »
‘HOOK 2’ Review – A Sharp Left Hook From...
The original HOOK ($1.99) had a very simple idea behind it. You were presented with a tangled mess of hooks and loops, and you needed to remove each one without snagging any others. Extremely simple at first, but as the puzzles rolled along,... | Read more »
‘Dicey Dungeons’ Mobile Version Launchin...
After a very long wait, Terry Cavanagh’s dungeon crawling roguelite deckbuiler hybrid experience Dicey Dungeons is coming to mobile platforms next week alongside a huge free DLC pack on all platforms. This DLC will be included in the mobile... | Read more »
Distract Yourself With These Great Mobil...
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
‘Danganronpa S: Ultimate Summer Camp’ is...
If you’ve been following Danganronp over the last few years, Spike Chunsoft celebrated its anniversary by bringing the series to mobile in the form of anniversary editions. After the first two released, there was a long delay for V3, but it finally... | Read more »
Out Now: ‘HOOK 2’, ‘Incoherence’, ‘Juras...
Each and every day new mobile games are hitting the App Store, and so each week we put together a big old list of all the best new releases of the past seven days. Back in the day the App Store would showcase the same games for a week, and then... | Read more »
Upcoming Mobile MMO RPG Shooter ‘Avatar:...
This past January a contingent of developers made up of Archosaur Games, Tencent, Lightstorm Entertainment, and Disney announced a new mobile game set in James Cameron’s Avatar universe titled Avatar: Reckoning. | Read more »
Culinary Platformer ‘Chefy-Chef’ Coming...
If your name is Chefy, it’s pretty much a given that you should be a chef. Such is the case with Chefy-Chef, a game from Bug Studio about a chef named Chefy who must travel to all sorts of exotic locations using a magical refrigerator in an effort... | Read more »
SwitchArcade Round-Up: Nintendo Direct H...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for June 29th, 2022. As the month winds to a close, we’ve got a bigger-than-usual Wednesday for both news and new games to check out. I’ve got some crib notes for yesterday’s Nintendo... | Read more »

Price Scanner via

2nd generation 4K Apple TVs with Siri remote...
Apple has restocked a full line of Certified Refurbished 2nd generation 32GB and 64GB 4K Apple TVs with Siri remotes for $30 off the cost of new models. Apple’s standard one-year warranty is included... Read more
Back in stock: Apple Watch Series 7 models fo...
Apple has restocked Certified Refurbished Apple Watch Series 7 WiFi-only models in their online store for $60-$70 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a... Read more
July 4th Sale at Expercom: $200 off any 16″ M...
Apple reseller Expercom has 16″ M1 Pro and M1 Max MacBook Pros available for $200 off MSRP as part of their July 4th sale. In addition to their MacBook Pro sale prices, take $50 off AppleCare+ when... Read more
10.2″ Apple iPads (WiFi models) are on sale f...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for up to $20-$50 off MSRP for a limited time. Their prices are the lowest price currently available for one of these iPads. All models are... Read more
10-Core M1 Pro 14″ MacBook Pros on sale for $...
B&H Photo is offering $200 discounts on Apple’s new 14″ M1 Pro MacBook Pros with 10-Core CPUs (16GB RAM/1TB SSDs). Free 1-2 day shipping is available to most US addresses, and both models are in... Read more
B&H has 16-inch M1 Pro MacBook Pros in st...
New Space Gray 16″ MacBook Pros with Apple’s M1 Pro CPUs are in stock and on sale today at B&H Photo for $200 off Apple’s MSRP. Sale prices are for M1 Pro models with 512GB or 1TB of SSD storage... Read more
Price drop! 13″ M1 MacBook Pro with 512GB SSD...
Amazon has dropped prices on recently-discontinued 13″ M1 MacBook Pros with a 512GB SSD by $200 off Apple’s original MSRP. Shipping is free: – 2020 13″ MacBook Pro (Space Gray or Silver) M1 CPU/512GB... Read more
Deal Alert! 14″ Apple MacBook Pros with M1 Pr...
Amazon has 14″ MacBook Pros with 8-Core M1 Pro CPUs back on sale for $200 off MSRP, only $1799. Shipping is free. Be sure to make your purchase from Amazon rather than a third-party seller: – 14″ M1... Read more
16″ MacBook Pros with Apple M1 Pro CPUs are b...
Amazon is discounting new 16″ MacBook Pros with 10-Core Apple M1 Pro CPUs by $200 off MSRP again today. Be sure to select Amazon as the seller rather than a third-party seller, and note that Amazon’s... Read more
13″ M1 MacBook Airs with 16GB of RAM availabl...
Apple has 13″ M1 MacBook Airs (8-Core CPU/7-Core GPU) in stock today with 16GB of RAM for $190 off MSRP, Certified Refurbished. Apple includes a standard one-year warranty with these models, each... Read more

Jobs Board

I/S Senior Engineer - *Apple* Systems Engin...
**19647BR** **Position Title:** I/S Senior Engineer - Apple Systems Engineering - Remote **Department:** Information Systems **Location:** Lakeland, FL between Read more
*Apple* IT Support Analyst - 2nd Shift - Zon...
Apple IT Support Analyst - 2nd Shift Professional Services Albany, New York Malta, New York Clifton Park, New York Menands, New York Syracuse, New York Watertown, Read more
Infotainment Certification Test Engineer (XC)...
…integration - CarPlay, android auto, MirrorLink, Baidu Carlife, MFi/iPod certification testing; Apple PPID preparation, Google HUCD and GTM preparation + 3 years of Read more
Workplace Services *Apple* Device Managemen...
…3350 Riverwood Parkway Suite 900, Atlanta, GA, 30339 USA **Workplace Services Apple Device Management** **Role Overview** Carrier is seeking an experienced and Read more
Physician Assistant - Certified, Primary Care...
Physician Assistant - Certified, Primary Care, Apple Valley (1.07FTE) + Job ID: 65766 + Department: AV Primary Care + City: Apple Valley, MN + Location: HP - Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.