Author: saqibkhan

  • TypeScript vs. JavaScript

    TypeScript and JavaScript are the most popular programming languages widely used in web development. If you are a web developer, you must have heard about them.

    Do you know the difference between JavaScript and TypeScript, or have you ever been confused about choosing between them? If yes, we have covered the difference between them, which one you should choose between them, and how to migrate from JavaScript to TypeScript.

    JavaScript

    Initially, in 1994, JavaScript was developed for the Netscape browser to add interactivity to web pages. After that, in 1997, the first standardized version of JavaScript was launched.

    In the starting phase, JavaScript was used to add interactivity to the web pages. For example, to add a click event, form submission event, etc. So, it was used with HTML and CSS and became a fundamental scripting language for them.

    Nowadays, JavaScript is also used for backend development. For example, NodeJS is used to create the backend of the web applications.

    In simple terms, JavaScript is a cross-platform programming language, which can be used to develop the frontend and backend of the application.

    Features of JavaScript

    Here are some basic features of JavaScript.

    • Dynamic Typing − JavaScript variables dont have fixed types. So, it provides the flexibility in assigning the values to the variables.
    • First-Class Functions − In JavaScript, functions can be expressions. So, it can be assigned to a variable, passed as arguments, and returned from other functions.
    • Prototypal Inheritance − JavaScript supports prototype-based inheritance, which can be achieved by modifying the object prototypes. However, it also supports class-based inheritance.
    • Asynchronous Programming − JavaScript supports asynchronous programming with callbacks, promises, and async/await.
    • Cross-platform support − JavaScript is supported by all modern web browsers and other platforms. It is also used to develop the front end and backend of web applications. So, it is a platform-independent programming language.

    Example

    In the code below, the add() function takes two numbers as an argument. In the function body, we sum the values of the parameters a and b and use the return keyword to return the summation of both parameters.

    // JavaScript example: Adding two numbersfunctionadd(a, b){return a + b;}console.log(add(5,10));// Output: 15

    The output of the above example code is as follows –

    15
    

    TypeScript

    TypeScript is very similar to JavaScript, and it has almost the same syntax as JavaScript. In 2012, Microsoft created TypeScript as an open-source project to solve the issues faced by developers while using JavaScript. So, TypeScript contains all the features that JavaScript has and contains some extra features to solve additional issues of typing.

    TypeScript has static typing which is more useful in large projects in which multiple developers are working together. Whenever you compile the TypeScript code, it compiles the code in JavaScript, and then you can use NodeJS to run the compiled TypeScript code.

    Features of TypeScript

    Here are some features of TypeScript, which are not available in JavaScript.

    • Static Typing − TypeScript allows you to specify types for each variable, function parameter, and return value. This feature helps in catching errors at compile time.
    • Interfaces − TypeScript is an object-oriented programming language, and it contains the interfaces to define the structure of objects that help in improving code readability and maintainability.
    • Classes and Inheritance − TypeScript supports classes and classical inheritance, making it easier to create complex structures.
    • Compatibility − TypeScript is compatible with all versions of JavaScript.
    • JavaScript Features − TypeScript is a superset of JavaScript. So, you can use all JavaScript features, methods, libraries, etc. in TypeScript.

    Example

    In the code below, we have defined the number type for the function parameters, which was not there in the JavaScript code. However, both code produces the same output.

    // TypeScript example: Adding two numbersfunctionadd(a:number, b:number):number{return a + b;}console.log(add(5,10));// Output: 15

    On compiling, it will generate the following JavaScript code.

    // TypeScript example: Adding two numbersfunctionadd(a, b){return a + b;}
    console.log(add(5,10));// Output: 15

    The output of the above example code is as follows –

    15
    

    Key Differences Between JavaScript and TypeScript

    The main difference between TypeScript and JavaScript is typing, as JavaScript has dynamic typing and TypeScript has static typing. However, we have covered some more differences between them in the table below.

    FeatureJavaScriptTypeScript
    TypingDynamic typingStatic typing
    CompilationInterpreted by browsers/Node.jsCompiled into JavaScript
    Error DetectionRuntime errorsCompile-time errors
    Tooling SupportBasicAdvanced (autocompletion, refactoring, etc.)
    Prototypal InheritanceUses prototypesSupports classes and classical inheritance
    Use CasesSmall to medium projects, quick prototypingLarge projects, complex applications
    Code MaintainabilityCan be harder in large codebasesEasier due to static typing and interfaces
    InterfacesNot natively supportedSupported, and improved code structure
    Type InferenceNot availableAvailable, reduces the need for explicit types
    Access ModifiersNot supportedSupports private, public, and protected modifiers
    Asynchronous ProgrammingCallbacks, Promises, async/awaitSame as JavaScript, with type safety

    When to Use JavaScript?

    JavaScript can be used in various situations, and here are some of them.

    • Smaller Projects − If you want to create smaller projects like static company or personal portfolio, you may use JavaScript.
    • Quick Prototyping − If you want to create a quick prototype of the application, you can use JavaScript instead of TypeScript. However, you can migrate JavaScript to TypeScript later.
    • Learning Curve − JavaScript is easier for beginners to pick up due to its simpler syntax and lack of strict typing requirements.

    When to Use TypeScript?

    TypeScript is well-suited for various situations:

    • Large Projects − When you are creating large or real-time projects, you should use TypeScript. In large projects, multiple developers work together. So, TypeScript makes it easier for them to know variable type, return type of function values, etc.
    • Code Maintainability − Makes maintaining and refactoring code easier with static typing and interfaces.
    • Error Detection − Allows for catching errors at compile-time rather than runtime, leading to more reliable code.
    • Compatibility − If you are already working with JavaScript libraries, TypeScript can be gradually introduced, providing a smooth transition.

    Both JavaScript and TypeScript are the most popular programming languages but can be used in various situations. JavaScript is beginner-friendly and can be used for prototyping applications. While TypeScript can be used for large real-time projects.

  • Basic Syntax

    Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A TypeScript program is composed of −

    • Modules
    • Functions
    • Variables
    • Statements and Expressions
    • Comments

    Your First TypeScript Code

    Let us start with the traditional Hello World example −

    var message:string="Hello World"console.log(message)

    On compiling, it will generate following JavaScript code.

    var message ="Hello World";console.log(message);
    • Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program.
    • Line 2 prints the variables value to the prompt. Here, console refers to the terminal window. The function log () is used to display text on the screen.

    Compile and Execute a TypeScript Program

    Let us see how to compile and execute a TypeScript program using Visual Studio Code. Follow the steps given below −

    Step 1 − Save the file with .ts extension. We shall save the file as Test.ts. The code editor marks errors in the code, if any, while you save it.

    Step 2 − Right-click the TypeScript file under the Working Files option in VS Codes Explore Pane. Select Open in Command Prompt option.

    Compile and Execute

    Step 3 − To compile the file use the following command on the terminal window.

    tsc Test.ts
    

    Step 4 − The file is compiled to Test.js. To run the program written, type the following in the terminal.

    node Test.js
    

    Compiler Flags

    Compiler flags enable you to change the behavior of the compiler during compilation. Each compiler flag exposes a setting that allows you to change how the compiler behaves.

    The following table lists some common flags associated with the TSC compiler. A typical command-line usage uses some or all switches.

    S.No.Compiler flag & Description
    1.–helpDisplays the help manual
    2.–moduleLoad external modules
    3.–targetSet the target ECMA version
    4.–declarationGenerates an additional .d.ts file
    5.–removeCommentsRemoves all comments from the output file
    6.–outCompile multiple files into a single output file
    7.–sourcemapGenerate a sourcemap (.map) files
    8.–module noImplicitAnyDisallows the compiler from inferring the any type
    9.–watchWatch for file changes and recompile them on the fly

    Note − Multiple files can be compiled at once.

    tsc file1.ts, file2.ts, file3.ts
    

    Identifiers in TypeScript

    Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are −

    • Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.
    • Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($).
    • Identifiers cannot be keywords.
    • They must be unique.
    • Identifiers are case-sensitive.
    • Identifiers cannot contain spaces.

    The following tables lists a few examples of valid and invalid identifiers −

    Valid identifiersInvalid identifiers
    firstNameVar
    first_namefirst name
    num1first-name
    $result1number

    TypeScript Keywords

    Keywords have a special meaning in the context of a language. The following table lists some keywords in TypeScript.

    breakasanyswitch
    caseifthrowelse
    varnumberstringget
    moduletypeinstanceoftypeof
    publicprivateenumexport
    finallyforwhilevoid
    nullsuperthisnew
    inreturntruefalse
    anyextendsstaticlet
    packageimplementsinterfacefunction
    newtryyieldconst
    continuedocatch

    Whitespace and Line Breaks

    TypeScript ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

    TypeScript is Case-sensitive

    TypeScript is case-sensitive. This means that TypeScript differentiates between uppercase and lowercase characters.

    Semicolons are optional

    Each line of instruction is called a statement. Semicolons are optional in TypeScript.

    Example

    console.log("hello world")console.log("We are learning TypeScript")

    A single line can contain multiple statements. However, these statements must be separated by a semicolon.

    Comments in TypeScript

    Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler.

    TypeScript supports the following types of comments −

    • Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment
    • Multi-line comments (/* */) − These comments may span multiple lines.

    Example

    //this is single line comment /* This is a  
       Multi-line comment 
    */

    TypeScript and Object Orientation

    TypeScript is Object-Oriented JavaScript. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. TypeScript supports these object oriented components too.

    • Object − An object is a real time representation of any entity. According to Grady Brooch, every object must have three features −
      • State − described by the attributes of an object
      • Behavior − describes how the object will act
      • Identity − a unique value that distinguishes an object from a set of similar such objects.
    • Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.
    • Method − Methods facilitate communication between objects.

    Example: TypeScript and Object Orientation

    classGreeting{greet():void{console.log("Hello World!!!")}}var obj =newGreeting(); 
    obj.greet();

    The above example defines a class Greeting. The class has a method greet (). The method prints the string Hello World on the terminal. The new keyword creates an object of the class (obj). The object invokes the method greet ().

    On compiling, it will generate following JavaScript code.

    var Greeting =(function(){functionGreeting(){}
       Greeting.prototype.greet=function(){console.log("Hello World!!!");};return Greeting;}());var obj =newGreeting();
    obj.greet()

    The output of the above program is given below −

    Hello World!!!
    
  • Environment Setup

    We already have set up TypeScript programming online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

    var message:string="Hello World"console.log(message)

    On compiling, it will generate following JavaScript code.

    var message ="Hello World";console.log(message);

    In this chapter, we will discuss how to install TypeScript on Windows platform. We will also explain how to install the Brackets IDE.

    You may test your scripts online by using The TypeScript at www.typescriptlang.org/Playground. The online editor shows the corresponding JavaScript emitted by the compiler.

    TypeScript Online Test

    You may try the following example using Playground.

    var num:number=12console.log(num)

    On compiling , it will generate following JavaScript code.

    var num =12;console.log(num);

    The output of the above program is given below −

    12
    

    Local Environment Setup

    Typescript is an Open Source technology. It can run on any browser, any host, and any OS. You will need the following tools to write and test a Typescript program −

    A Text Editor

    The text editor helps you to write your source code. Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors used may vary with Operating Systems.

    The source files are typically named with the extension .ts

    The TypeScript Compiler

    The TypeScript compiler is itself a .ts file compiled down to JavaScript (.js) file. The TSC (TypeScript Compiler) is a source-to-source compiler (transcompiler / transpiler).

    TypeScript Compiler

    The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation.

    However, the compiler rejects any raw JavaScript file passed to it. The compiler deals with only .ts or .d.ts files.

    This TypeScript tutorial is based on the latest typescript 5.5.2 version.

    Installing Node.js

    Node.js is an open source, cross-platform runtime environment for server-side JavaScript. Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript engine to execute code. You may download Node.js source code or a pre-built installer for your platform. Node is available here − https://nodejs.org/en/download

    Installation on Windows

    Follow the steps given below to install Node.js in Windows environment.

    Step 1 − Download and run the .msi installer for Node.

    Download and Run Installer

    Step 2 − To verify if the installation was successful, enter the command node v in the terminal window.

    Verify Installation

    Step 3 − Type the following command in the terminal window to install TypeScript.

    npm install -g typescript
    
    Install TypeScript

    Installation on Mac OS X

    To install node.js on Mac OS X, you can download a pre-compiled binary package which makes a nice and easy installation. Head over to http://nodejs.org/ and click the install button to download the latest package.

    Download Latest Package

    Install the package from the .dmg by following the install wizard which will install both node and npm. npm is Node Package Manager which facilitates installation of additional packages for node.js.

    Install Node

    Installation on Linux

    You need to install a number of dependencies before you can install Node.js and NPM.

    • Ruby and GCC. Youll need Ruby 1.8.6 or newer and GCC 4.2 or newer.
    • Homebrew. Homebrew is a package manager originally designed for Mac, but its been ported to Linux as Linuxbrew. You can learn more about Homebrew at http://brew.sh/ and Linuxbrew at http://brew.sh/linuxbrew

    Once these dependencies are installed, you may install Node.js by using the following command on the terminal −

    brew install node.
    

    IDE Support

    Typescript can be built on a plethora of development environments like Visual Studio, Sublime Text 2, WebStorm/PHPStorm, Eclipse, Brackets, etc. Visual Studio Code and Brackets IDEs are discussed here. The development environment used here is Visual Studio Code (Windows platform).

    Visual Studio Code

    This is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VScode is available at − https://code.visualstudio.com/

    Installation on Windows

    Step 1 − Download Visual Studio Code for Windows.

    Download Visual Studio Code

    Step 2 − Double-click on VSCodeSetup.exe Launch Setup Process to launch the setup process. This will only take a minute.

    Setup Wizard

    Step 3 − A screenshot of the IDE is given below.

    IDE

    Step 4 − You may directly traverse to the files path by right clicking on the file → open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer.

    Traverse Files Path

    Installation on Mac OS X

    Visual Studio Codes Mac OS X specific installation guide can be found at

    https://code.visualstudio.com/Docs/editor/setup

    Installation on Linux

    Linux specific installation guide for Visual Studio Code can be found at

    https://code.visualstudio.com/Docs/editor/setup

    Brackets

    Brackets is a free open-source editor for web development, created by Adobe Systems. It is available for Linux, Windows and Mac OS X. Brackets is available at http://brackets.io/

    Brackets

    TypeScript Extensions for Brackets

    Brackets supports extensions for adding extra functionality via the Extension Manager. The following steps explain installing TypeScript extensions using the same.

    • Post installation, click on the extension manager icon Extension Manager on the right-hand side of the editor. Enter typescript in the search box.
    • Install the Brackets TSLint and Brackets TypeScript plugins.
    TypeScript Extensions

    You can run DOS prompt / shell within Brackets itself by adding one more extension Brackets Shell.

    Brackets Shell

    Upon installation, you will find an icon of shell on the right-hand side of the editor Shell. Once you click on the icon, you will see the shell window as shown below −

    Shell Window

    Note − Typescript is also available as a plugin for Visual Studio 2012 and 2013 environments (https://www.typescriptlang.org/#Download).VS 2015 and above includes Typescript plugin by default.

    Now, you are all set!!!

  • Overview

    JavaScript was introduced as a language for the client side. The development of Node.js has marked JavaScript as an emerging server-side technology too. However, as JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse the code. Moreover, its failure to embrace the features of Object Orientation, strong type checking and compile-time error checks prevents JavaScript from succeeding at the enterprise level as a full-fledged server-side technology. TypeScript was presented to bridge this gap.

    What is TypeScript?

    By definition, TypeScript is JavaScript for application-scale development.

    TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

    TypeScript Figure

    Features of TypeScript

    TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution.

    TypeScript supports other JS libraries. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries.

    JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files.

    TypeScript is portable. TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesnt need a dedicated VM or a specific runtime environment to execute.

    TypeScript and ECMAScript

    The ECMAScript specification is a standardized specification of a scripting language. There are six editions of ECMA-262 published. Version 6 of the standard is codenamed “Harmony”. TypeScript is aligned with the ECMAScript6 specification.

    TypeScript and ECMAScript

    TypeScript adopts its basic language features from the ECMAScript5 specification, i.e., the official specification for JavaScript. TypeScript language features like Modules and class-based orientation are in line with the EcmaScript 6 specification. Additionally, TypeScript also embraces features like generics and type annotations that arent a part of the EcmaScript6 specification.

    Why Use TypeScript?

    TypeScript is superior to its other counterparts like CoffeeScript and Dart programming languages in a way that TypeScript is extended JavaScript. In contrast, languages like Dart, CoffeeScript are new languages in themselves and require language-specific execution environment.

    The benefits of TypeScript include −

    • Compilation − JavaScript is an interpreted language. Hence, it needs to be run to test that it is valid. It means you write all the codes just to find no output, in case there is an error. Hence, you have to spend hours trying to find bugs in the code. The TypeScript transpiler provides the error-checking feature. TypeScript will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run.
    • Strong Static Typing − JavaScript is not strongly typed. TypeScript comes with an optional static typing and type inference system through the TLS (TypeScript Language Service). The type of a variable, declared with no type, may be inferred by the TLS based on its value.
    • TypeScript supports type definitions for existing JavaScript libraries. TypeScript Definition file (with .d.ts extension) provides definition for external JavaScript libraries. Hence, TypeScript code can contain these libraries.
    • TypeScript supports Object Oriented Programming concepts like classes, interfaces, inheritance, etc.

    Components of TypeScript

    At its heart, TypeScript has the following three components −

    • Language − It comprises of the syntax, keywords, and type annotations.
    • The TypeScript Compiler − The TypeScript compiler (tsc) converts the instructions written in TypeScript to its JavaScript equivalent.
    • The TypeScript Language Service − The “Language Service” exposes an additional layer around the core compiler pipeline that are editor-like applications. The language service supports the common set of a typical editor operations like statement completions, signature help, code formatting and outlining, colorization, etc.
    TypeScript Components

    Declaration Files

    When a TypeScript script gets compiled, there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. The concept of declaration files is analogous to the concept of header files found in C/C++. The declaration files (files with .d.ts extension) provide intellisense for types, function calls, and variable support for JavaScript libraries like jQuery, MooTools, etc.

  • Command Line Arguments in C

    In any C program, there may be multiple functions, but the main() function remains the entry point from where the execution starts. While the other functions may have one or more arguments and a return type, the main() function is generally written with no arguments. The main() function also has a return value of “0”.

    intmain(){......return0;}

    Inside the main() function, there may be scanf() statements to let the user input certain values, which are then utilized.

    #include <stdio.h>intmain(){int a;scanf("%d",&a);printf("%d", a);return0;}

    What are Command Line Arguments?

    Instead of invoking the input statement from inside the program, it is possible to pass data from the command line to the main() function when the program is executed. These values are called command line arguments.

    Command line arguments are important for your program, especially when you want to control your program from outside, instead of hard coding those values inside the code.

    Let us suppose you want to write a C program “hello.c” that prints a “hello” message for a user. Instead of reading the name from inside the program with scanf(), we wish to pass the name from the command line as follows −

    C:\users\user>hello Prakash
    

    The string will be used as an argument to the main() function and then the “Hello Prakash” message should be displayed.

    argc and argv

    To facilitate the main() function to accept arguments from the command line, you should define two arguments in the main() function argc and argv[].

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

    intmain(int argc,char*argv[]){......return0;}

    The argc argument should always be non-negative. The argv argument is an array of character pointers to all the arguments, argv[0] being the name of the program. After that till “argv [argc – 1]“, every element is a command-line argument.

    Open any text editor and save the following code as “hello.c” −

    #include <stdio.h>intmain(int argc,char* argv[]){printf("Hello %s", argv[1]);return0;}

    The program is expected to fetch the name from argv[1] and use it in the printf() statement.

    Instead of running the program from the Run menu of any IDE (such as VS code or CodeBlocks), compile it from the command line −

    C:\Users\user>gcc -c hello.c -o hello.o
    

    Build the executable −

    C:\Users\user>gcc -o hello.exe hello.o
    

    Pass the name as a command line argument −

    C:\Users\user>hello Prakash
    Hello Prakash
    

    If working on Linux, the compilation by default generates the object file as “a.out“. We need to make it executable before running it by prefixing “./” to it.

    $ chmod a+x a.o
    $ ./a.o Prakash
    

    Example

    Given below is a simple example that checks if there is any argument supplied from the command line and takes action accordingly −

    #include <stdio.h>intmain(int argc,char*argv[]){if(argc ==2){printf("The argument supplied is %s\n", argv[1]);}elseif(argc >2){printf("Too many arguments supplied.\n");}else{printf("One argument expected.\n");}}
    Output

    When the above code is compiled and executed with a single argument, it produces the following output −

    $./a.out testing
    The argument supplied is testing.
    

    When the above code is compiled and executed with two arguments, it produces the following output −

    $./a.out testing1 testing2
    Too many arguments supplied.
    

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

    $./a.out
    One argument expected
    

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

    Passing Numeric Arguments from the Command Line

    Let us write a C program that reads two command line arguments, and performs the addition of argv[1] and argv[2].

    Example

    Start by saving the code below −

    #include <stdio.h>intmain(int argc,char* argv[]){int c = argv[1]+ argv[2];printf("addition: %d", c);return0;}

    Output

    When we try to compile, you get the error message −

    error: invalid operands to binary + (have 'char *' and 'char *')
     int c = argv[1]+argv[2];
    
         ~~~~~~~~~~~~~~

    This is because the “+” operator cannot have non-numeric operands.

    The atoi() Function

    To solve this issue, we need to use the library function atoi() that converts the string representation of a number to an integer.

    Example

    The following example shows how you can use the atoi() function in a C program −

    #include <stdio.h>#include <stdlib.h>intmain(int argc,char* argv[]){int c =atoi(argv[1])+atoi(argv[2]);printf("addition: %d", c);return0;}
    Output

    Compile and build an executive from “add.c” and run from the command line, passing numeric arguments −

    C:\Users\user>add 10 20
    addition: 30
    

    Example

    You pass all the command line arguments separated by a space, but if the argument itself has a space, then you can pass such arguments by putting them inside double quotes (” “) or single quotes (‘ ‘).

    In this example, we will pass a command line argument enclosed inside double quotes −

    #include <stdio.h>intmain(int argc,char*argv[]){printf("Program name %s\n", argv[0]);if(argc ==2){printf("The argument supplied is %s\n", argv[1]);}elseif(argc >2){printf("Too many arguments supplied.\n");}else{printf("One argument expected.\n");}}
    Output

    When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output −

    $./a.out "testing1 testing2"
    
    Program name ./a.out
    The argument supplied is testing1 testing2
    
  • Random Number Generation in C

    The stdlib.h library in C includes the rand() function that returns an integer randomly, between “0” and the constant RAND_MAX.

    The rand() function generates pseudo-random numbers. They are not truly random. The function works on Linear Congruential Generator (LCG) algorithm.

    intrand(void);

    Example 1

    The following code calls the rand() function thrice, each time it is likely to come with a different integer −

    #include <stdio.h>#include<stdlib.h>intmain(){printf("%ld\n",rand());printf("%ld\n",rand());printf("%ld\n",rand());return0;}

    Output

    Run the code and check its output −

    41
    18467
    6334
    

    The rand() function doesn’t have a built-in mechanism to set the seed. By default, it might use a system specific value (often based on the time the program starts).

    Note: The srand() function is used to improve the randomness by providing a seed to the rand() function.

    Example 2

    The following program returns a random number between 0 to 100. The random integer returned by the rand() function is used as a numerator and its mod value with 100 is calculated to arrive at a random number that is less than 100.

    #include <stdio.h>#include<stdlib.h>intmain(){for(int i =1; i <=5; i++){printf("random number %d: %d \n", i,rand()%100);}return0;}

    Output

    Run the code and check its output −

    random number 1: 41
    random number 2: 67
    random number 3: 34
    random number 4: 0
    random number 5: 69
    

    Example 3

    You can also obtain a random number between a given range. You need to find the mod value of the result of rand() divided by the range span, add the result to the lower value of the range.

    #include <stdio.h>#include<stdlib.h>intmain(){int i, num;int lower=50, upper=100;for(i =1; i <=5; i++){
    
      num =(rand()%(upper - lower +1))+ lower;printf("random number %d: %d \n", i,num);}return0;}</code></pre>

    Output

    Run the code and check its output −

    random number 1: 91
    random number 2: 55
    random number 3: 60
    random number 4: 81
    random number 5: 94
    

    The srand() Function

    The stdlib.h library also includes the srand() function that is used to seed the rand() functions random number generator.

    You would use the following syntax to use the srand() function −

    voidsrand(unsigned seed);

    OR

    intsrand(unsignedint seed);

    The seed parameter is an integer value to be used as seed by the pseudo-random number generator algorithm.

    Note: If srand() is not initialized, then the seed value in rand() function is set as srand(1).

    Usually, the srand() function is used with the value returned by time(NULL) (which represents the current time since the epoch) as a parameter to improve the randomness of the pseudo-random numbers generated by rand() in C.

    Since the time value changes all the time, this will have different seed values, leading to more varied random sequences. As a result, if you generate random number multiple times, then it will likely result in different random value every time.

    Example 1

    Take a look at the following example −

    #include <stdio.h>#include<stdlib.h>#include <time.h>intmain(){srand(time(NULL));printf("Random number: %d \n",rand());return0;}

    Output

    Every time a new random integer between 0 to RAND_MAX will be displayed.

    Random number: 1436786055 
    

    Example 2

    We can include srand() to generate a random number between a given range.

    #include <stdio.h>#include<stdlib.h>#include <time.h>intmain(){int i, num;time_t t;int lower =100, upper =200;srand((unsigned)time(&t));for(i =1; i <=5; i++){
    
      num =(rand()%(upper - lower +1))+ lower;printf("random number number %d: %d \n", i, num);}return0;}</code></pre>

    Output

    Run the code and check its output −

    random number number 1: 147
    random number number 2: 171
    random number number 3: 173
    random number number 4: 112
    random number number 5: 181
    

    The random number generation offered by rand() function is not truly random. With the same seed, you'll always get the same sequence. It also has a limited range as it generates random numbers within a specific range (0 to RAND_MAX).

    To improving the Randomness, you need to use a good seed value with high unpredictability like system time or a high-resolution timer. You can also use third party libraries for wider range random numbers.

  • Static Keyword

    What is static Keyword in C?

    The static keyword in C is one of the storage class specifiers which has different meanings based on the context in which it is used.

    The “static” keyword is used to declare a static variable as well as to define a static function. When declared as “static”, a variable represents a static storage class.

    static function is available only inside the program file (with “.c” extension) in which it is defined. One cannot use the “extern” keyword to import a static function into another file.

    Uses of static Keyword

    The following are the different uses of the static keyword

    • Static Local Variable: When a local variable is declared with the static keyword, its lifetime will be till the end of the program and it retains the value between the function calls.
    • Static Global Variable: When a global variable is declared with the static keyword, it can only be accessed within the same file. It is useful when you want to make a global variable as a private global variable to the file in which it is declared.
    • Static Functions: When you function is declared as a static function, its scope will be limited to the file in which the function is declared. You cannot access the function in other files.

    Static Variables (static Keyword with Variables)

    When a variable is declared as static, it is initialized only once. The compiler persists with the variable till the end of the program. A static variable is also used to store data that should be shared between multiple functions.

    Here are some of the important points to note regarding a static variable −

    • The compiler allocates space to the static variable in computers main memory.
    • Unlike auto, a static variable is initialized to zero and not garbage.
    • A static variable is not re-initialized on every function call, if it is declared inside a function.
    • A static variable has local scope.

    Example of static Keyword with Variables

    In the following example, the variable “x” in the counter() function is declared as static. It is initialized to “0” when the counter() function is called for the first time. On each subsequent call, it is not re-initialized; instead it retains the earlier value.

    #include <stdio.h>intcounter();intmain(){counter();counter();counter();return0;}intcounter(){staticint x;printf("Value of x as it enters the function: %d\n", x);
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    When you run this code, it will produce the following output −

    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 1
    Incremented value of x: 2
    Value of x as it enters the function: 2
    Incremented value of x: 3
    

    A static variable is similar to a global variable, as both of them, are initialized to 0 (for numeric types) or null pointers (for pointers) unless explicitly assigned. However, the scope of the static variable is restricted to the function or block in which it is declared.

    Static Functions (static Keyword with Functions)

    By default, every function is treated as global function by the compiler. They can be accessed anywhere inside a program.

    When prefixed with the keyword “static” in the definition, we get a static function that has a scope limited to its object file (the compiled version of a program saved with “.c” extension). This means that the static function is only visible in its object file.

    A static function can be declared by placing the keyword “static” before the function name.

    Example of static Keyword with Function (in Multiple Files)

    Open a console application with the CodeBlocks IDE. Add two files “file1.c” and “main.c”. The contents of these files are given as follows −

    Contents of “file1.c” −

    staticvoidstaticFunc(void){printf("Inside the static function staticFunc() ");}

    Contents of “main.c” −

    #include <stdio.h>#include <stdlib.h>intmain(){staticFunc();return0;}

    Now, if the above console application project is built, then we will get an error, i.e., “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file.

    Example of static Keyword with Function (in the Same File)

    The following program demonstrates how static functions work in a C program −

    #include <stdio.h>staticvoidstaticFunc(void){printf("Inside the static function staticFunc() ");}intmain(){staticFunc();return0;}

    Output

    The output of the above program is as follows −

    Inside the static function staticFunc()
    

    In the above program, the function staticFunc() is a static function that prints “Inside the static function staticFunc()”. The main() function calls staticFunc(). This program works correctly as the static function is called only from its own object file.

    Example of static Keyword with Multiple Functions

    You can have multiple static functions in the same object file, as illustrated in the following example −

    #include <stdio.h>#include <stdlib.h>#include <math.h>// define the static functionstaticintsquare(int num){return num * num;}staticvoidvoidfn(){printf("From inside the static function.\n");}staticintintfn(int num2){returnsqrt(num2);}intmain(){int n1, val;
       n1 =16;
       val =square(n1);// Call voidfn static functionprintf("The square of the %d : %d\n", n1, val);voidfn();// Call intfn static function
       val =intfn(n1);printf("The square root of the %d : %d\n", n1, val);return0;}

    Output

    When you run this code, it will produce the following output −

    The square of the 16: 256
    From inside the static function.
    The square root of the 16: 4
    
  • Math Functions

    C Math Functions

    C language provides various functions to perform mathematical operations on numbers such as finding trigonometric ratios, calculating log and exponentials, rounding the numbers, etc.. To use these math functions in a C program, you need to include math.h header file.

    We have categorized math functions into the following categories −

    • Trigonometric Functions
    • Inverse Trigonometric Functions
    • Hyperbolic Functions
    • Exponentiation and Logarithmic Functions
    • Floating-Point Functions
    • Power and Square Root Functions
    • Rounding Functions
    • Modulus Functions

    Trigonometric Functions

    The math.h library defines the function sin()cos(), and tan() that return the respective trigonometric ratios, sine, cosine and tangent of an angle.

    These functions return the respective ratio for a given double type representing the angle expressed in radians. All the functions return a double value.

    doublesin(double x)doublecos(double x)doubletan(double x)

    For all the above functions, the argument “x” is the angle in radians.

    Example

    The following example shows how you can use trigonometric functions in C −

    #include <stdio.h>#include <math.h>#define PI 3.14159265intmain(){double x, sn, cs, tn, val;
    
       x =45.0;
       val = PI /180;
    
       sn =sin(x*val);
       cs =cos(x*val);
       tn =tan(x*val);printf("sin(%f) : %f\n", x, sn);printf("cos(%f) : %f\n", x, cs);printf("tan(%f) : %f\n", x, tn);return(0);}

    Output

    When you run this code, it will produce the following output −

    sin(45.000000) : 0.707107
    cos(45.000000) : 0.707107
    tan(45.000000) : 1.000000
    

    Inverse Trigonometric Functions

    The math.h library also includes inverse trigonometric functions, also known as arcus functions or anti-trigonometric functions. They are the inverse functions of basic trigonometric functions. For example, asin(x) is equivalent to $&bsol;mathrm{sin^{-1}(x)}$. The other inverse functions are acos(), atan() and atan2().

    The following asin() function returns the arc sine of “x” in the interval [-pi/2, +pi/2] radians −

    doubleasin(double x)

    The following acos() function returns principal arc cosine of “x” in the interval [0, pi] radians −

    doubleacos(double x)

    The following atan() function returns the principal arc tangent of “x” in the interval [-pi/2, +pi/2] radians.

    doubleatan(double x)

    Example 1

    The following example demonstrates how you can use inverse trigonometric functions in a C program −

    #include <stdio.h>#include <math.h>#define PI 3.14159265intmain(){double x, asn, acs, atn, val;
    
       x =0.9;
       val =180/PI;
    
       asn =asin(x);
       acs =acos(x);
       atn =atan(x);printf("asin(%f) : %f in radians\n", x, asn);printf("acos(%f) : %f in radians\n", x, acs);printf("atan(%f) : %f in radians\n", x, atn);
    
       asn =(asn *180)/ PI;
       acs =(acs *180)/ PI;
       atn =(atn *180)/ PI;printf("asin(%f) : %f in degrees\n", x, asn);printf("acos(%f) : %f in degrees\n", x, acs);printf("atan(%f) : %f in degrees\n", x, atn);return(0);}

    Output

    When you run this code, it will produce the following output −

    asin(0.900000) : 1.119770 in radians
    acos(0.900000) : 0.451027 in radians
    atan(0.900000) : 0.732815 in radians
    asin(0.900000) : 64.158067 in degrees
    acos(0.900000) : 25.841933 in degrees
    atan(0.900000) : 41.987213 in degrees
    

    The atan2() function returns the arc tangent in radians of “y/x” based on the signs of both values to determine the correct quadrant.

    double atan2(double y, double x)

    This function returns the principal arc tangent of “y / x” in the interval [-pi, +pi] radians.

    Example 2

    Take a look at the following example −

    #include <stdio.h>#include <math.h>#define PI 3.14159265intmain(){double x, y, ret, val;
    
       x =-7.0;
       y =7.0;
       val =180.0/ PI;
    
       ret =atan2(y,x)* val;printf("The arc tangent of x = %lf, y = %lf ", x, y);printf("is %lf degrees\n", ret);return(0);}

    Output

    Run the code and check its output −

    The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees
    

    Hyperbolic Functions

    In Mathematics, hyperbolic functions are similar to trigonometric functions but are defined using the hyperbola rather than the circle. The math.h header file provides sinh(), cosh(), and tanh() functions.

    doublesinh(double x)

    This function returns hyperbolic sine of x.

    doublecosh(double x)

    This function returns hyperbolic cosine of x.

    doubletanh(double x)

    This function returns hyperbolic tangent of x.

    Example

    The following example shows how you can use hyperbolic functions in a C program −

    #include <stdio.h>#include <math.h>#define PI 3.14159265intmain(){double x,val, sh, ch, th;
    
       x =45;
       val = PI/180.0;
    
       sh =sinh(x*val);
       ch =cosh(x*val);
       th =tanh(x*val);printf("The sinh(%f) = %lf\n", x, sh);printf("The cosh(%f) = %lf\n", x, ch);printf("The tanh(%f) = %lf\n", x, th);return(0);}

    Output

    Run the code and check its output −

    The sinh(45.000000) = 0.868671
    The cosh(45.000000) = 1.324609
    The tanh(45.000000) = 0.655794
    

    Exponentiation and Logarithmic Functions

    The “math.h” library includes the following functions related to exponentiation and logarithms −

    exp() Function: It returns the value of e raised to the xth power. (Value of e – Eulers number is 2.718 approx)

    doubleexp(double x)

    log() Function: It returns the natural logarithm (base-e logarithm) of “x”.

    doublelog(double x)

    Note that Logarithmic functions are equivalent to the exponential functions inverse.

    log10() Function: It returns the common logarithm (base-10 logarithm) of “x”.

    doublelog10(double x)

    Example

    The following example shows how you can use exponentiation and logarithmic functions in a C program −

    #include <stdio.h>#include <math.h>#define PI 3.14159265intmain(){double x =2;double e, ln, ls;
       e =exp(2);
       ln =log(e);printf("exp(%f): %f log(%f): %f\n",x, e, e, ln);
    
       ln =log(x);printf("log(%f): %f\n",x,ln);
       ls =log10(x);printf("log10(%f): %f\n",x,ls);return(0);}

    Output

    When you run this code, it will produce the following output −

    exp(2.000000): 7.389056 log(7.389056): 2.000000
    log(2.000000): 0.693147
    log10(2.000000): 0.301030
    

    Floating-Point Functions

    The frexp() and ldexp() functions are used for floating-point manipulation.

    frexp() Function

    The “math.h” header file also includes the frexp() function. It breaks a floating-point number into its significand and exponent.

    doublefrexp(double x,int*exponent)

    Here, “x” is the floating point value to be computed and “exponent” is the pointer to an int object where the value of the exponent is to be stored.

    This function returns the normalized fraction.

    Example

    Take a look at the following example −

    #include <stdio.h>#include <math.h>intmain(){double x =1024, fraction;int e;
    
       fraction =frexp(x,&e);printf("x = %.2lf = %.2lf * 2^%d\n", x, fraction, e);return(0);}

    Output

    Run the code and check its output −

    x = 1024.00 = 0.50 * 2^11
    

    ldexp() Function

    The ldexp() function combines a significand and an exponent to form a floating-point number. Its syntax is as follows −

    doubleldexp(double x,int exponent)

    Here, “x” is the floating point value representing the significand and “exponent” is the value of the exponent. This function returns (x * 2 exp)

    Example

    The following example shows how you can use this ldexp() function in a C program −

    #include <stdio.h>#include <math.h>intmain(){double x, ret;int n;
    
       x =0.65;
       n =3;
       ret =ldexp(x ,n);printf("%f * 2 %d = %f\n", x, n, ret);return(0);}

    Output

    Run the code and check its output −

    0.650000 * 2^3 = 5.200000
    

    Power and Square Root Functions

    The pow() and sqrt() functions are used to calculate the power and square root of the given number.

    pow() Function

    This function returns x raised to the power of y i.e. xy.

    doublepow(double x,double y)

    sqrt() Function

    returns the square root of x.

    doublesqrt(double x)

    The sqrt(x) function returns a value which is same as pow(x, 0.5)

    Example

    The following example shows how you can use the pow() and sqrt() functions in a C program −

    #include <stdio.h>#include <math.h>intmain(){double x =9, y=2;printf("Square root of %lf is %lf\n", x,sqrt(x));printf("Square root of %lf is %lf\n", x,pow(x,0.5));printf("%lf raised to power %lf\n", x,pow(x, y));return(0);}

    Output

    When you run this code, it will produce the following output −

    Square root of 9.000000 is 3.000000
    Square root of 9.000000 is 3.000000
    9.000000 raised to power 81.000000
    

    Rounding Functions

    The math.h library includes ceil()floor(), and round() functions that round off the given floating point number.

    ceil() Function

    This returns the smallest integer value greater than or equal to x.

    doubleceil(double x)

    This function returns the smallest integral value not less than x.

    floor() Function

    This function returns the largest integer value less than or equal to x.

    doublefloor(double x)

    Parameter x : This is the floating point value. This function returns the largest integral value not greater than x.

    round() Function

    This function is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value.

    doubleround(double x )

    The value returned is the nearest integer represented as floating point

    Example

    The following example demonstrates how you can use the rounding functions in a C program −

    #include <stdio.h>#include <math.h>intmain(){float val1, val2, val3, val4;
    
       val1 =1.2;
       val2 =1.6;
       val3 =2.8;
       val4 =-2.3;printf("ceil(%lf) = %.1lf\n", val1,ceil(val1));printf("floor(%lf) = %.1lf\n", val2,floor(val2));printf("ceil(%lf) = %.1lf\n", val3,ceil(val3));printf("floor(%lf) = %.1lf\n", val4,floor(val4));printf("round(%lf) = %.1lf\n", val1,round(val1));printf("round(%lf) = %.1lf", val4,round(val4));return(0);}
    Output

    When you run this code, it will produce the following output −

    ceil(1.200000) = 2.0
    floor(1.600000) = 1.0
    ceil(2.800000) = 3.0
    floor(-2.300000) = -3.0
    round(1.200000) = 1.0
    round(-2.300000) = -2.0
    

    Modulus Functions

    The “math.h” library includes the following functions in this category:

    modf() Function

    The modf() function returns the fraction component (part after the decimal), and sets integer to the integer component.

    doublemodf(double x,double*integer)

    Here, “x” is the floating point value and “integer” is the pointer to an object where the integral part is to be stored.

    This function returns the fractional part of “x” with the same sign.

    Example

    Take a look at the following example −

    #include <stdio.h>#include <math.h>intmain(){double x, fractpart, intpart;
    
       x =8.123456;
       fractpart =modf(x,&intpart);printf("Integral part = %lf\n", intpart);printf("Fraction Part = %lf \n", fractpart);return(0);}
    Output

    When you run this code, it will produce the following output −

    Integral part = 8.000000
    Fraction Part = 0.123456
    

    fmod() Function

    The fmod() function returns the remainder of x divided by y.

    doublefmod(double x,double y)

    Here, “x” is the numerator and “y” is the denominator. The function returns remainder of “x / y“.

    Example

    Take a look at the following example −

    #include <stdio.h>#include <math.h>intmain(){float a, b;int c;
       a =9.2;
       b =3.7;
       c =2;printf("Remainder of %f / %d is %lf\n", a, c,fmod(a,c));printf("Remainder of %f / %f is %lf\n", a, b,fmod(a,b));return(0);}
    Output

    When you run this code, it will produce the following output −

    Remainder of 9.200000 / 2 is 1.200000
    Remainder of 9.200000 / 3.700000 is 1.800000
    

    Note that the modulus operator (%) works only with integer operands.

  • Command Execution

    Command Execution in C

    Command execution in C is used to execute the system command using the C program. The system commands are executed by using the system() function which is a library function of stdlib.h header file.

    By using the system() function, you can execute the Windows/Linux terminal commands inside a C program.

    Syntax

    The following is the syntax to execute system commands −

    system(char*command);

    Example of Command Execution

    The following code shows the execution of ls command using system() function in C language.

    #include <stdio.h>#include<stdlib.h>#include<string.h>intmain(){char cmd[10];strcpy(cmd,"dir C:\\users\\user\\*.c");system(cmd);return0;}

    Output

    Run the code and check its output −

    C:\Users\user>dir *.c
     Volume in drive C has no label.
     Volume Serial Number is 7EE4-E492
    
     Directory of C:\Users\user
    
    04/01/2024  01:30 PM               104 add.c
    04/02/2024  01:37 PM               159 add1.c
    04/02/2024  01:37 PM               259 array.c
    04/02/2024  01:37 PM               149 main.c
    04/02/2024  01:37 PM               180 recursion.c
    04/02/2024  01:37 PM               241 struct.c
    04/02/2024  01:37 PM               172 voidptr.c
    
               7 File(s)           1,264 bytes
               0 Dir(s)  139,073,761,280 bytes 

    exec Family of Functions in C

    The exec family of functions have been introduced in the “unistd.h” header file. These functions are used to execute a file, and they replace the current process image with a new process image once they are called.

    The following are the functions of exec family in C −

    1. execl() Function
    2. execlp() Function
    3. execle() Function
    4. execv() Function
    5. execvp() Function
    6. execve() Function

    1. execl() Function

    The execl() function’s first argument is the executable file as its first argument. The next arguments will be available to the file when it’s executed. The last argument has to be NULL.

    intexecl(constchar*pathname,constchar*arg,...,NULL)

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="/usr/bin/echo";char*arg1 ="Hello world!";execl(file, file, arg1,NULL);return0;}

    The echo command in Linux is being invoked through the C code.

    Output

    Save, compile, and execute the above program −

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    

    2. execlp() Function

    The execlp() function is similar to the execl() function. It uses the PATH environment variable to locate the file. Hence, the path to the executable file needn’t be given.

    intexeclp(constchar*file,constchar*arg,...,NULL)

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="echo";char*arg1 ="Hello world!";execlp(file, file, arg1,NULL);return0;}

    Output

    Here, echo is already located in the PATH environment variable. Save, compile and run from the terminal.

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    

    3. execle() Function

    In the execle() function, we can pass environment variables to the function, and it’ll use them. Its prototype is like this −

    intexecle(constchar*pathname,constchar*arg,...,NULL,char*const envp[])

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="/usr/bin/bash";char*arg1 ="-c";char*arg2 ="echo $ENV1 $ENV2!";char*const env[]={"ENV1 = Hello","ENV2 = World",NULL};execle(file, file, arg1, arg2,NULL, env);return0;}

    Output

    Save, compile, and run from the terminal −

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    

    4. execv() Function

    The execv() function receives a vector of arguments that will be available to the executable file. In addition, the last element of the vector has to be NULL:

    intexecv(constchar*pathname,char*const argv[])

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="/usr/bin/echo";char*const args[]={"/usr/bin/echo","Hello world!",NULL};execv(file, args);return0;}

    Output

    Save, compile, and execute the above program −

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    

    5. execvp() Function

    The execvp() has the following syntax −

    intexecvp(constchar*file,char*const argv[])

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="echo";char*const args[]={"/usr/bin/echo","Hello world!",NULL};execvp(file, args);return0;}

    Output

    Save, compile, and execute the above program −

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    

    6. execve() Function

    In addition to environment variables, we can pass other arguments to execve() function as a NULL-terminated vector −

    intexecve(constchar*pathname,char*const argv[],char*const envp[])

    Example

    Take a look at the following example −

    #include <unistd.h>intmain(void){char*file ="/usr/bin/bash";char*const args[]={"/usr/bin/bash","-c","echo Hello $ENV!",NULL};char*const env[]={"ENV=World",NULL};execve(file, args, env);return0;}

    Output

    Save, compile, and execute the above program −

    $ gcc hello.c -o hello
    $ ./hello
    Hello world!
    
  • Variable Arguments

    Sometimes, you may come across a situation, when you want to have a function that can accept a variable number of arguments (parameters) instead of a predefined number of arguments. The C programming language provides a solution for this situation.

    Read this chapter to learn how you can define a function that can accept a variable number of parameters based on your requirement.

    The following example shows the definition of such a function −

    intfunc(int,...){......}intmain(){func(1,2,3);func(1,2,3,4);}

    It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (…) and the one just before the ellipses is always an int which will represent the total number variable arguments passed.

    To get such a functionality, you need to use the stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments.

    Follow the steps given below −

    • Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments.
    • Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.
    • Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file.
    • Use va_arg macro and va_list variable to access each item in argument list.
    • Use a macro va_end to clean up the memory assigned to va_list variable.

    Example

    Let us now follow the above steps and write down a simple function which can take the variable number of parameters and return their average −

    #include <stdio.h>#include <stdarg.h>doubleaverage(int num,...){
    
       va_list valist;double sum =0.0;int i;/* initialize valist for num number of arguments */va_start(valist, num);/* access all the arguments assigned to valist */for(i =0; i < num; i++){
    
      sum +=va_arg(valist,int);}/* clean memory reserved for valist */va_end(valist);return sum/num;}intmain(){printf("Average of 2, 3, 4, 5 = %f\n",average(4,2,3,4,5));printf("Average of 5, 10, 15 = %f\n",average(3,5,10,15));}</code></pre>

    Output

    When the above code is compiled and executed, it produces the following output −

    Average of 2, 3, 4, 5 = 3.500000
    Average of 5, 10, 15 = 10.000000
    

    It should be noted that the function average() has been called twice and each time the first argument represents the total number of variable arguments being passed. Only ellipses are used to pass variable number of arguments.