SlideShare a Scribd company logo
1 of 32
Download to read offline
A Quick Taste of C
For Applesoft programmers
Why Use C on an Apple //?
• Your code will run faster if you code in C versus
AppleSoft
• It is easier to code in C than assembly language
(in my opinion)
• If you are careful, you can write C code which
works on an Apple // and on modern OS’s (Mac
OS X, Windows, Linux, etc)
• There are good cross-compiling tools for C
C Compiler vs Applesoft
Interpreter
• Applesoft is an interpreter
• This means that the Apple // is running a program which
reads and executes your program.
• An interpreter introduces a significant performance penalty
• C is a compiled language
• This means your code is turned into machine code which
runs “on the metal” on your Apple //
• But if you make a mistake in your code, it can lead to
crashes which are hard to figure out
Compilation Process
This is what happens when your C code is turned into a
binary which you can run.
file1.c
file2.c
file1.oCompiler
Compiler
file2.o
BinaryLinker
Mac OS X
BinaryCopy
Real or
emulated
Apple //
Comments in Your Code
• You can add comments in your Applesoft code:
10	
  REM	
  THIS	
  IS	
  A	
  COMMENT	
  IN	
  BASIC	
  
• There are two ways to add comments in C:
/*	
  This	
  is	
  a	
  multiline	
  comment	
  
which	
  starts	
  from	
  a	
  slash	
  star	
  
and	
  goes	
  to	
  a	
  star	
  slash	
  */	
  
//	
  This	
  is	
  a	
  single	
  line	
  comment
No Line Numbers?
• Unlike Applesoft, there are no line numbers in C code
• But how does this work?
• Although C does have a goto statement, it jumps to
a location with a name, not a line number.
• Instead of gosub, you create and call functions
referenced by name, not a line number.
• Loops and if statements can enclose a block of
statements. We will see examples later.
Where does the program
start?
• In Applesoft, execution starts from the lowest
numbered line of code (line 10 perhaps)
• But C does not have line numbers so where does
execution start?
• C defines a special function called “main” which is
where execution begins.
• When a C executable is launched, the main function is
called and the program ends when the main function
returns.
But What Is A Function?
• The previous slide introduced the “main function” without defining functions.
• In C, a function is similar to a subroutine in Applesoft.
• But, a function is more structured than an Applesoft subroutine:
• Every function has a name. You use the name to call the function.
• Every function has their own “local variables”. Variables in Applesoft are
“global”. C has global variables but C functions can have their own
variables which are private.
• Every function takes zero or more inputs that are special local variables.
They are set to a value which comes from the caller of the function.
• Every function can return a value back to the caller.
The main() Function
• Here is a pretty standard way to define the main function
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• The main function here:
• Takes no input arguments. That is what “void” means.
• Returns an integer to the caller. That is what “int” means.
• The code for this function is between the curly braces.
Another function
• Here is another function in C:
int	
  square(int	
  x)	
  
{	
  
	
  	
  	
  	
  return	
  x	
  *	
  x;	
  
}	
  
• This function:
• Takes an integer from the caller and puts it into a local variable
called “x”.
• Returns that number multiplied by itself back to the caller.
What About The Semi-
Colons?
• In Applesoft, you can use a semi-colon at the end of a
print statement to prevent it from outputting a new line
at the end.
• In C, every statement in code must end with a semi-
colon character.
• If you forget it, the C compiler won’t understand your
code and it will give you errors.
• The C compiler needs the semi-colon to tell where
each statement ends and a new one starts.
Variables In Applesoft
• You can just start using a variable. The first time
you reference it, it is created.
• The variable name can be as long as you like
but only the first two characters are relevant.
• The type of the variable is encoded in the name
with special characters.
Variables in C
• You must “declare” your variables before you can use them. They are not just
implicitly created when first used.
• A variable can have a name that is as long as you like. All characters of the
name are used, not just the first two.
• You can use lots of kinds of characters in the name:
• They must start with a lower or upper case letter or an underscore
character.
• After the first character, you can use letters, numbers or the underscore
character.
• C is case sensitive
• The declaration tells you the type of variable.
Variable Types
Applesoft C
Integers X% = 5 int x = 5;
Floating point Y = 1.5 float y = 1.5;
Strings Z$ = “HELLO” char z[] = “hello”;
Note: cc65 does not support floating point!
Strings
• The previous slide made it seem like C has a string variable type but
that really is not true.
• C has a “char” variable type which is a variable which holds a single
character.
• You can do arrays of char’s in order to create a string.
• In C, the standard is that a string is zero or more characters followed by
a “null terminator” which is ASCII zero (ie CHR$(0) in Applesoft).
• Or a string can be a “pointer to a char” - I will not try to explain that
right now…
• Strings, arrays and pointers are all intertwined and if you understand
them, you pretty much understand C.
Printing Text
• To print text in C, we need to use the “standard I/O
functions”.
• But all functions (like all variables) need to be declared.
• There is a short-hand to declare all of the standard I/O
functions. You just tell the compiler to “include” them as
though you typed them:
#include	
  <stdio.h>	
  
• The “stdio.h” file will be inserted as though you typed it in
your source file. That way, you can get all of the standard I/O
declarations.
Printing Text
• To print text, use the “printf” function. Here is a complete example:
#include	
  <stdio.h>	
  
int	
  main	
  (void)	
  
{	
  
	
  	
  	
  	
  printf(“HELLO,	
  WORLD!n”);	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• This is the first function call you have seen. We are calling the function
printf() with a single value. That value is a string (inside quotes).
• The “n” in the string is replaced by the C compiler with new-line character.
So, you get a new line at the end of the printed text.
Printing Integers
• Here is an example of printing an integer variable
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  int	
  x	
  =	
  10;	
  
	
  	
  	
  	
  printf(“x	
  =	
  %dn”,	
  x);	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• The %d character is special to printf(). When it sees a %d, it looks at the
next input argument. It expects to find an integer and it replaces the %d
with the value. In this case it prints “x = 10”.
Printing Characters
• Here is an example of printing a character variable
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  char	
  x	
  =	
  ‘e’;	
  
	
  	
  	
  	
  printf(“x	
  =	
  %cn”,	
  x);	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• The %c character is special to printf(). When it sees a %c, it looks at the
next input argument. It expects to find an character and it replaces the %c
with the value. In this case, it prints “x = e”.
Printing Strings
• Here is an example of printing a character variable
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  char	
  x[]	
  =	
  “hello”;	
  
	
  	
  	
  	
  printf(“x	
  =	
  %sn”,	
  x);	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• The %s character is special to printf(). When it sees a %s, it looks at the
next input argument. It expects to find a string and it replaces the %s with
the value. In this case, it prints “x = hello”.
Getting Input
• To read a string from the user, you need to define a
string buffer to read into.
• In Applesoft, strings grow or shrink as required to hold
them.
• In C, you need to manage the size of your own strings
and make sure you don’t put more data into a string
than it will hold
• This is the well known “buffer overflow” problem that
has lead to so many security problems.
Getting Input
• Here is an example of reading a line of text:
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  char	
  buffer[80];	
  //	
  80	
  bytes	
  
	
  	
  	
  	
  fgets(buffer,	
  sizeof(buffer),	
  stdin);	
  
	
  	
  	
  	
  printf(“You	
  typed	
  =	
  %sn”,	
  buffer);	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• The fgets() function gets a string from a file (File GET String or fgets).
• The “file” it reads from is the special file “stdin” which is short for standard input which
is generally the keyboard.
If Statements
• Here is what an if statement looks like:
int	
  x	
  =	
  10;	
  
if	
  (x	
  ==	
  10)	
  {	
  
	
  	
  	
  	
  printf(“x	
  is	
  10!n”);	
  
}	
  
• Note that the curly braces are optional if only one statement exists in the
body of the if.
• The indenting is not required but can help you and others read and
understand your code.
• Note the double equal signs which means “equals” where single equal
signs means “assignment”.
If Statements
• Your if statements can have multiple statements inside the curly braces:
int	
  x	
  =	
  10;	
  
if	
  (x	
  ==	
  10)	
  {	
  
	
  	
  	
  	
  x	
  =	
  x	
  *	
  2;	
  
	
  	
  	
  	
  printf(“x	
  was	
  10!n”);	
  
}	
  
• Here if x is 10, the two statements in the curly braces will be exectued. After
that, execution continues after the end of the curly braces.
• If x is not 10, then those two statements are skipped. Execution continues
after the end of the curly braces.
If Statements
• If statements can have “else” clauses.
int	
  x	
  =	
  10;	
  
if	
  (x	
  ==	
  10)	
  {	
  
	
  	
  	
  	
  x	
  =	
  x	
  *	
  2;	
  
	
  	
  	
  	
  printf(“x	
  was	
  10!n”);	
  
}	
  else	
  {	
  
	
  	
  	
  	
  printf(“x	
  was	
  not	
  10!n”);	
  
}	
  
• Here if x is 10, the two statements in the curly braces will be exectued. After that,
execution skips the printf() in the else clause and continues after the end of the else
curly braces.
• If x is not 10, then those two statements are skipped. The printf() in the else curly brace
is executed instead and execution continues after the else curly braces.
If Statements
• If statements can be nested:
int	
  x	
  =	
  10;	
  
int	
  y	
  =	
  5;	
  
if	
  (x	
  ==	
  10)	
  {	
  
	
  	
  	
  	
  if	
  (y	
  ==	
  5)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“x	
  is	
  10	
  and	
  y	
  is	
  5n”);	
  
	
  	
  	
  	
  }	
  else	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“x	
  is	
  10	
  and	
  y	
  is	
  not	
  5n”);	
  
	
  	
  	
  	
  }	
  
}	
  else	
  {	
  
	
  	
  	
  	
  if	
  (y	
  ==	
  5)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“x	
  is	
  not	
  10	
  and	
  y	
  is	
  5n”);	
  
	
  	
  	
  	
  }	
  else	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“x	
  is	
  not	
  10	
  and	
  y	
  is	
  not	
  5n”);	
  
	
  	
  	
  	
  }	
  
}
For Loops
• Here is the classic “count from 1 to 100” in C using a for loop:
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  int	
  i;	
  
	
  	
  	
  	
  for	
  (i	
  =	
  1;	
  i	
  <=	
  100;	
  i++)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“%dn”,	
  i);	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  return	
  0;	
  
}	
  
• “i++” is a shortcut which is the same as saying “i = i + 1”
For Loops
• A for loop in C has four different components:
for	
  (A;	
  B;	
  C)	
  {	
  
	
  	
  	
  	
  D;	
  
}	
  
• The “A” above is the initialization phase of the for loop. It is executed only once before the
first execution through the loop.
• The next thing which happens is that “B” is executed. If B is a statement which returns true,
then the loop executes.
• At this point “D” executes. D is one or more statements which make up the body of the loop.
• After that, “C” executes. This is generally where the loop counter is incremented. But, you
can do just about what ever you want in this statement.
• Again, “B” is executed and if it again returns true, the loop executes again. As soon as B
returns false, the for loop is done and execution continues after the curly braces.
While Loops
• Here is the classic “count from 1 to 100” in C using a while loop:
#include	
  <stdio.h>	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  int	
  i	
  =	
  1;	
  
	
  	
  	
  	
  while	
  (i	
  <=	
  100)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“%dn”,	
  i);	
  
	
  	
  	
  	
  	
  	
  	
  	
  i++;	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  return	
  0;	
  
}
While Loops
• A while loop in C has two different components:
while	
  (A)	
  {	
  
	
  	
  	
  	
  B;	
  
}	
  
• The first thing which happens is that “A” is executed. If A is a
statement which returns true, then the loop executes.
• At this point “B” executes. B is one or more statements which make
up the body of the loop.
• Again, “A” is executed and if it again returns true, the loop executes
again. As soon as A returns false, the while loop is done and
execution continues after the curly braces.
Putting It Together
• Here is a C program to calculate the squares from 1 to 100:
#include	
  <stdio.h>	
  
int	
  square(int	
  x)	
  
{	
  
	
  	
  	
  	
  return	
  x	
  *	
  x;	
  
}	
  
int	
  main(void)	
  
{	
  
	
  	
  	
  	
  int	
  i;	
  
	
  	
  	
  	
  for	
  (i	
  =	
  1;	
  i	
  <=	
  100;	
  i++)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  printf(“%d	
  squared	
  is	
  %dn”,	
  i,	
  square(i));	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  return	
  0;	
  
}
Now Go and Write Some C Code!

More Related Content

What's hot

What's hot (17)

LISP: Input And Output
LISP: Input And OutputLISP: Input And Output
LISP: Input And Output
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
What is c
What is cWhat is c
What is c
 
Lesson 6 php if...else...elseif statements
Lesson 6   php if...else...elseif statementsLesson 6   php if...else...elseif statements
Lesson 6 php if...else...elseif statements
 
Lesson 4 constant
Lesson 4  constantLesson 4  constant
Lesson 4 constant
 
Ch3 Formatted Input/Output
Ch3 Formatted Input/OutputCh3 Formatted Input/Output
Ch3 Formatted Input/Output
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Ch7 Basic Types
Ch7 Basic TypesCh7 Basic Types
Ch7 Basic Types
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
Assignment10
Assignment10Assignment10
Assignment10
 
Ch8 Arrays
Ch8 ArraysCh8 Arrays
Ch8 Arrays
 
Paolo Galeone - Dissecting tf.function to discover auto graph strengths and s...
Paolo Galeone - Dissecting tf.function to discover auto graph strengths and s...Paolo Galeone - Dissecting tf.function to discover auto graph strengths and s...
Paolo Galeone - Dissecting tf.function to discover auto graph strengths and s...
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-c
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 

Similar to A Quick Taste of C

Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 

Similar to A Quick Taste of C (20)

A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
C programming language
C programming languageC programming language
C programming language
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
001 Lecture-11-C-Traps-and-Pitfalls-part-1.pdf
001 Lecture-11-C-Traps-and-Pitfalls-part-1.pdf001 Lecture-11-C-Traps-and-Pitfalls-part-1.pdf
001 Lecture-11-C-Traps-and-Pitfalls-part-1.pdf
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Python ppt
Python pptPython ppt
Python ppt
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
 
Vba Class Level 1
Vba Class Level 1Vba Class Level 1
Vba Class Level 1
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Chap 1 and 2
Chap 1 and 2Chap 1 and 2
Chap 1 and 2
 
First Class
First ClassFirst Class
First Class
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C tutorial
C tutorialC tutorial
C tutorial
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

A Quick Taste of C

  • 1. A Quick Taste of C For Applesoft programmers
  • 2. Why Use C on an Apple //? • Your code will run faster if you code in C versus AppleSoft • It is easier to code in C than assembly language (in my opinion) • If you are careful, you can write C code which works on an Apple // and on modern OS’s (Mac OS X, Windows, Linux, etc) • There are good cross-compiling tools for C
  • 3. C Compiler vs Applesoft Interpreter • Applesoft is an interpreter • This means that the Apple // is running a program which reads and executes your program. • An interpreter introduces a significant performance penalty • C is a compiled language • This means your code is turned into machine code which runs “on the metal” on your Apple // • But if you make a mistake in your code, it can lead to crashes which are hard to figure out
  • 4. Compilation Process This is what happens when your C code is turned into a binary which you can run. file1.c file2.c file1.oCompiler Compiler file2.o BinaryLinker Mac OS X BinaryCopy Real or emulated Apple //
  • 5. Comments in Your Code • You can add comments in your Applesoft code: 10  REM  THIS  IS  A  COMMENT  IN  BASIC   • There are two ways to add comments in C: /*  This  is  a  multiline  comment   which  starts  from  a  slash  star   and  goes  to  a  star  slash  */   //  This  is  a  single  line  comment
  • 6. No Line Numbers? • Unlike Applesoft, there are no line numbers in C code • But how does this work? • Although C does have a goto statement, it jumps to a location with a name, not a line number. • Instead of gosub, you create and call functions referenced by name, not a line number. • Loops and if statements can enclose a block of statements. We will see examples later.
  • 7. Where does the program start? • In Applesoft, execution starts from the lowest numbered line of code (line 10 perhaps) • But C does not have line numbers so where does execution start? • C defines a special function called “main” which is where execution begins. • When a C executable is launched, the main function is called and the program ends when the main function returns.
  • 8. But What Is A Function? • The previous slide introduced the “main function” without defining functions. • In C, a function is similar to a subroutine in Applesoft. • But, a function is more structured than an Applesoft subroutine: • Every function has a name. You use the name to call the function. • Every function has their own “local variables”. Variables in Applesoft are “global”. C has global variables but C functions can have their own variables which are private. • Every function takes zero or more inputs that are special local variables. They are set to a value which comes from the caller of the function. • Every function can return a value back to the caller.
  • 9. The main() Function • Here is a pretty standard way to define the main function int  main(void)   {          return  0;   }   • The main function here: • Takes no input arguments. That is what “void” means. • Returns an integer to the caller. That is what “int” means. • The code for this function is between the curly braces.
  • 10. Another function • Here is another function in C: int  square(int  x)   {          return  x  *  x;   }   • This function: • Takes an integer from the caller and puts it into a local variable called “x”. • Returns that number multiplied by itself back to the caller.
  • 11. What About The Semi- Colons? • In Applesoft, you can use a semi-colon at the end of a print statement to prevent it from outputting a new line at the end. • In C, every statement in code must end with a semi- colon character. • If you forget it, the C compiler won’t understand your code and it will give you errors. • The C compiler needs the semi-colon to tell where each statement ends and a new one starts.
  • 12. Variables In Applesoft • You can just start using a variable. The first time you reference it, it is created. • The variable name can be as long as you like but only the first two characters are relevant. • The type of the variable is encoded in the name with special characters.
  • 13. Variables in C • You must “declare” your variables before you can use them. They are not just implicitly created when first used. • A variable can have a name that is as long as you like. All characters of the name are used, not just the first two. • You can use lots of kinds of characters in the name: • They must start with a lower or upper case letter or an underscore character. • After the first character, you can use letters, numbers or the underscore character. • C is case sensitive • The declaration tells you the type of variable.
  • 14. Variable Types Applesoft C Integers X% = 5 int x = 5; Floating point Y = 1.5 float y = 1.5; Strings Z$ = “HELLO” char z[] = “hello”; Note: cc65 does not support floating point!
  • 15. Strings • The previous slide made it seem like C has a string variable type but that really is not true. • C has a “char” variable type which is a variable which holds a single character. • You can do arrays of char’s in order to create a string. • In C, the standard is that a string is zero or more characters followed by a “null terminator” which is ASCII zero (ie CHR$(0) in Applesoft). • Or a string can be a “pointer to a char” - I will not try to explain that right now… • Strings, arrays and pointers are all intertwined and if you understand them, you pretty much understand C.
  • 16. Printing Text • To print text in C, we need to use the “standard I/O functions”. • But all functions (like all variables) need to be declared. • There is a short-hand to declare all of the standard I/O functions. You just tell the compiler to “include” them as though you typed them: #include  <stdio.h>   • The “stdio.h” file will be inserted as though you typed it in your source file. That way, you can get all of the standard I/O declarations.
  • 17. Printing Text • To print text, use the “printf” function. Here is a complete example: #include  <stdio.h>   int  main  (void)   {          printf(“HELLO,  WORLD!n”);          return  0;   }   • This is the first function call you have seen. We are calling the function printf() with a single value. That value is a string (inside quotes). • The “n” in the string is replaced by the C compiler with new-line character. So, you get a new line at the end of the printed text.
  • 18. Printing Integers • Here is an example of printing an integer variable #include  <stdio.h>   int  main(void)   {          int  x  =  10;          printf(“x  =  %dn”,  x);          return  0;   }   • The %d character is special to printf(). When it sees a %d, it looks at the next input argument. It expects to find an integer and it replaces the %d with the value. In this case it prints “x = 10”.
  • 19. Printing Characters • Here is an example of printing a character variable #include  <stdio.h>   int  main(void)   {          char  x  =  ‘e’;          printf(“x  =  %cn”,  x);          return  0;   }   • The %c character is special to printf(). When it sees a %c, it looks at the next input argument. It expects to find an character and it replaces the %c with the value. In this case, it prints “x = e”.
  • 20. Printing Strings • Here is an example of printing a character variable #include  <stdio.h>   int  main(void)   {          char  x[]  =  “hello”;          printf(“x  =  %sn”,  x);          return  0;   }   • The %s character is special to printf(). When it sees a %s, it looks at the next input argument. It expects to find a string and it replaces the %s with the value. In this case, it prints “x = hello”.
  • 21. Getting Input • To read a string from the user, you need to define a string buffer to read into. • In Applesoft, strings grow or shrink as required to hold them. • In C, you need to manage the size of your own strings and make sure you don’t put more data into a string than it will hold • This is the well known “buffer overflow” problem that has lead to so many security problems.
  • 22. Getting Input • Here is an example of reading a line of text: #include  <stdio.h>   int  main(void)   {          char  buffer[80];  //  80  bytes          fgets(buffer,  sizeof(buffer),  stdin);          printf(“You  typed  =  %sn”,  buffer);          return  0;   }   • The fgets() function gets a string from a file (File GET String or fgets). • The “file” it reads from is the special file “stdin” which is short for standard input which is generally the keyboard.
  • 23. If Statements • Here is what an if statement looks like: int  x  =  10;   if  (x  ==  10)  {          printf(“x  is  10!n”);   }   • Note that the curly braces are optional if only one statement exists in the body of the if. • The indenting is not required but can help you and others read and understand your code. • Note the double equal signs which means “equals” where single equal signs means “assignment”.
  • 24. If Statements • Your if statements can have multiple statements inside the curly braces: int  x  =  10;   if  (x  ==  10)  {          x  =  x  *  2;          printf(“x  was  10!n”);   }   • Here if x is 10, the two statements in the curly braces will be exectued. After that, execution continues after the end of the curly braces. • If x is not 10, then those two statements are skipped. Execution continues after the end of the curly braces.
  • 25. If Statements • If statements can have “else” clauses. int  x  =  10;   if  (x  ==  10)  {          x  =  x  *  2;          printf(“x  was  10!n”);   }  else  {          printf(“x  was  not  10!n”);   }   • Here if x is 10, the two statements in the curly braces will be exectued. After that, execution skips the printf() in the else clause and continues after the end of the else curly braces. • If x is not 10, then those two statements are skipped. The printf() in the else curly brace is executed instead and execution continues after the else curly braces.
  • 26. If Statements • If statements can be nested: int  x  =  10;   int  y  =  5;   if  (x  ==  10)  {          if  (y  ==  5)  {                  printf(“x  is  10  and  y  is  5n”);          }  else  {                  printf(“x  is  10  and  y  is  not  5n”);          }   }  else  {          if  (y  ==  5)  {                  printf(“x  is  not  10  and  y  is  5n”);          }  else  {                  printf(“x  is  not  10  and  y  is  not  5n”);          }   }
  • 27. For Loops • Here is the classic “count from 1 to 100” in C using a for loop: #include  <stdio.h>   int  main(void)   {          int  i;          for  (i  =  1;  i  <=  100;  i++)  {                  printf(“%dn”,  i);          }          return  0;   }   • “i++” is a shortcut which is the same as saying “i = i + 1”
  • 28. For Loops • A for loop in C has four different components: for  (A;  B;  C)  {          D;   }   • The “A” above is the initialization phase of the for loop. It is executed only once before the first execution through the loop. • The next thing which happens is that “B” is executed. If B is a statement which returns true, then the loop executes. • At this point “D” executes. D is one or more statements which make up the body of the loop. • After that, “C” executes. This is generally where the loop counter is incremented. But, you can do just about what ever you want in this statement. • Again, “B” is executed and if it again returns true, the loop executes again. As soon as B returns false, the for loop is done and execution continues after the curly braces.
  • 29. While Loops • Here is the classic “count from 1 to 100” in C using a while loop: #include  <stdio.h>   int  main(void)   {          int  i  =  1;          while  (i  <=  100)  {                  printf(“%dn”,  i);                  i++;          }          return  0;   }
  • 30. While Loops • A while loop in C has two different components: while  (A)  {          B;   }   • The first thing which happens is that “A” is executed. If A is a statement which returns true, then the loop executes. • At this point “B” executes. B is one or more statements which make up the body of the loop. • Again, “A” is executed and if it again returns true, the loop executes again. As soon as A returns false, the while loop is done and execution continues after the curly braces.
  • 31. Putting It Together • Here is a C program to calculate the squares from 1 to 100: #include  <stdio.h>   int  square(int  x)   {          return  x  *  x;   }   int  main(void)   {          int  i;          for  (i  =  1;  i  <=  100;  i++)  {                  printf(“%d  squared  is  %dn”,  i,  square(i));          }          return  0;   }
  • 32. Now Go and Write Some C Code!