Objective C Command Line Arguments - Objective C

What are Objective C Command-Line Arguments?

Some values passed to the command line programs when they are executed are called command line arguments.
These are important in a program especially when you want to control the program form outside of hard coding those inside the code.
The command line arguments are handled using main() function arguments where

  • argc refers to the number of arguments passed
  • argv[] is a pointer array, which points to each argument passed to the program.

A simple example is illustrated to check if there is any argument supplied from the command line and take action accordingly:

The above code is compiled and executed with a single argument, say "testing", the following result is produced.

The above code is compiled and executed with two arguments, say testing1 and testing2, it produces the following result.

When the above code is compiled and executed without passing any argument, it produces the following result.

It should be noted that

  • argv[0] holds the name of the program itself
  • argv[1] is a pointer to the first command-line argument supplied *argv[n] is the last argument.
  • If no arguments are supplied, argc will be one, otherwise if you pass one argument, then argc is set at 2.

All the command line arguments are separated by a space, but if argument itself has a space, then you can pass such arguments by putting them inside double quotes "" or single quotes ''.

The above example is rewritten where, we will print program name and pass a command-line argument by putting inside double quotes:

The above code is compiled and executed with a single argument separated by space but inside double quotes say "Testing1 Testing2", it produces the following result.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Objective C Topics