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.
- Open a terminal window and navigate to your desired work subdirectory.
- Open a text editor; Copy then paste the boxes below into your editor.
- Save the first block of code below as 'goc'. Save the second as 'main.c'.
- In the terminal window, make shell script 'goc' executable: "chmod +x goc"
- Invoke the compile script with the line: "./goc main.c pgm4"
- Invoke the newly-created program with "./pgm4 123"
- 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
/* '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.