We took care in 'pgm3' to not reveal a BUG! Now's the time to point this out, and in the bargain, to look at logical testing, branching, conditional program flow.

 

  1. Open a terminal window and navigate to your desired work subdirectory.
  2. Open a text editor; Copy then paste the boxes below into your editor.
  3. Save the first block of code below as 'goc'.  Save the second as 'main.c'.
  4. In the terminal window, make shell script 'goc' executable:  "chmod +x goc"
  5. Invoke the compile script with the line:   "./goc main.c pgm4"
  6. Invoke the newly-created program with "./pgm4 123"
  7. Test different command-line parameters: "./pgm4 apple", './pgm4', './pgm4 219'

 

   NOTE: Our 'goc' compiling script has changed. We can specify
the source-code filename as well as name for executable.  

 

 

#!/bin/bash
# syntax: ./goc source.c pgmname
# flag the compiler to provide more error and warning checks
sourcename=$1
pgmname=$2
gcc $sourcename -Wall -o $pgmname

 

(right-click to download)

/* 'pgm4' source */
#include <stdio.h>
#include <stdlib.h>

// argc = count of arguments argv = the individual arguments - type char string
int main(int argc, char *argv[]) {
int value1;

if (argc != 2) {
   printf("This program expects ONE argument on the command line\n");
   printf("Quitting.\n");
   return(-1);
   }

value1 = atoi(argv[1]);
if (value1 == 0) {
   printf("Cannot make sense of the command line argument\n"); 
   printf("Quitting.\n");
   return(-2);
   }

printf("The number you gave me is %d\n", value1);
return(0);
}

 

In this article we've got our first look at logical tests '!=' (is not equal?) and '==' (is equal?).  Those new to the 'C' language will naturally think when testing for equal, the '=' is used. The statement "if (num 1 = num2)" actually tries to assign the value of 'num2' to 'num1'; the compiler will throw a warning on this. The correct syntax:  "if (num1 == num2)" is correct.