Operators in C

#vpsinghrajput

Overview of the C Operators

The C operators fall into the following categories:
  • Postfix operators, which follow a single operand only.
  • Unary prefix operators, which precede with a single operand.
  • Binary operators, which take two operands and perform a variety of logical and arithmetic operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression only.
  • Assignment operators, which only assign a value to a variable.
  • The comma operator, which gives guarantees left-to-right evaluation of comma-separated expressions
To create more complex expressions,variables and constants can be used in conjunction with C operators. The following tables describes different operators available in c
Operator  Example  Description/Meaning 
()   f()   Function call 
[]   a[10]   Array reference 
->   a  ="">a> Structure and union member selection 
.   s.a   Structure and union member selection 
+ [unary]  +a   Value of a 
- [unary]  -a   Negative of a 
* [unary]  *a   Reference to object at address a 
& [unary]  &a   Address of a 
~a   One's complement of a 
++ [prefix]  ++a   The value of a after increment 
++ [postfix]  a++   The value of a before increment 
- - [prefix]  -a   The value of a after decrement 
- - [postfix]  a-   The value of a before decrement 
sizeof   sizeof (t1)   Size in bytes of object with type t1 
sizeof   sizeof e   Size in bytes of object having the type of expression e 
+ [binary]
- [binary]
* [binary]
/ % 
a + b
a - b
a * b
a / b
a % b  
a plus b
a minus b
a times b
a divided by b
Remainder of a/b 
>>
<< 
a >> b
a << b  
a, right-shifted b bits
a, left-shifted b bits 
<
>
<=
>=
==
!=  
a < b
a > b
a <= b
a >= b
a == b
a != b  
1 if a < b; 0 otherwise
1 if a > b; 0 otherwise
1 if a <= b; 0 otherwise
1 if a >= b; 0 otherwise
1 if a equal to b; 0 otherwise
1 if a not equal to b; 0 otherwise 
& [binary]
|
a & b
a | b
a ^ b  
Bitwise AND of a and b
Bitwise OR of a and b
Bitwise XOR (exclusive OR) of a and b 
&&
||
!  
a && b
a || b
!a  
Logical AND of a and b (yields 0 or 1)
Logical OR of a and b (yields 0 or 1)
Logical NOT of a (yields 0 or 1) 
?:  a ? e1 : e2   Expression e1 if a is nonzero;
Expression e2 if a is zero 
=
+=
-=
*=
/=
%=
>>=
<<=
&=
|=
^=
a = b
a += b
a -= b
a *= b
a /= b
a %= b
a >>= b
a <<= b
a &= b
a |= b
a ^= b
e1,e2  
a, after b is assigned to it
a plus b (assigned to a)
a minus b (assigned to a)
a times b (assigned to a)
a divided by b (assigned to a)
Remainder of a/b (assigned to a)
a, right-shifted b bits (assigned to a)
a, left-shifted b bits (assigned to a)
a AND b (assigned to a)
a OR b (assigned to a)
a XOR b (assigned to a)
e2 (e1 evaluated first) 


Precedence of C Operators

Category  Operator  Associativity 
Postfix  () [] -> . ++ - -   Left to right 
Unary  + - ! ~ ++ - - (type) * & sizeof   Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   << >>  Left to right 
Relational   < <= > >=  Left to right 
Equality   == !=  Left to right 
Bitwise AND  Left to right 
Bitwise XOR  Left to right 
Bitwise OR  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  Left to right 

Variables in C

#vpsinghrajput

LIKE MOST PROGRAMMING LANGUAGES

, C is able to use and process named variables and their contents. Variables are simply names used to refer to some location in memory - a location that holds a value with which we are working. It may help to think of variables as a placeholder for a value. You can think of a variable as being equivalent to its assigned value..


  1. Variables in C are memory locations with help of which we can be assigned values and are given names .

  2. To store data in memory for later use,we use variables.

  3. In C, a variable must have to be declared before it can be used.

  4. You can declare Variables at the start of any block of code, but most are found at the start of each function.

  5. Most local variables are destroyed on return from that function and created when the function is called.

  6. A declaration begins with the type, followed by the name of one or more than one variables. 




    You can name a variable anything you like as long as it includes only letters, numbers or underscores and does not start with a number. It is a good idea to keep your variable names less than 32 characters long to save time on typing them out and for compiler compatibility reasons. Variables must always be declared at the top before any other commands are used. Now let's declare an integer variable called a and a character variable called b.:
    int main()
    {
    int a;
    char b;
    return 0;
    }
    C keeps a small set of keywords for its own use only.These keywords are given below:
    auto break case char const continue default do
    double else enum extern float for goto if
    int long register return short signed sizeof static
    struct switch typedef union unsigned void volatile while

    Identifiers in C

    Identifiers" or "symbols" are the names you supply for variables, types,labels, and functions in your program. Identifier names must differ in case and spelling from any keywords. You cannot use keywords as the identifiers; they are reserved for special use only. You create an identifier by specifying it in the declaration of a variable,function,or type. In this example which is given below result is an identifier for an integer variable, and printf and main are identifier names for functions.
    Identifiers provide names for the given language elements:

    1. Functions
    2. Function parameters
    3. Macros and macro parameters
    4. Type definitions
    5. Objects
    6. Labels
    7. Enumerated types and enumerators
    8. Structure and union names
    #include

    int main()
    {
    int result;

    if ( result != 0 )
    printf_s( "Bad file handle\n" );
    }


    Variable declarations

    Variables are of three different types which are as follows:
    1. Global Variable
    2. Local Variable
    3. Static Variable
    4. Global Variable:
      The C programming language has an extensive system for declaring variables of different types. The rules for the more complex types can be confusing at times, due to the decisions taken over their design. The principal decision is that the declaration of a variable should be similar, syntactically, to its use (declaration reflects use) . Declare it outside of all the functions if you want to declare a global variable. The function will use the variable that was declared within it and ignore the global one,if a variable of the same name is declared both within a function and outside of it.
      Local Variable:
      Inside the specific function that creates them,these variables only exist. They are unknown to to the main program and to the other functions. In this case,they are normally implemented using a stack. Local variables cease to exist once if the function that created them is completed. Each time a function is executed or called,they are recreated.
      Variable declarations show up in three places:

      • Outside a function. These declarations declare global variables which are visible throughout the program (i.e. they have global scope). Use of global variables is always a big mistake.

      • In the header of a function in the argument list . These variables are the parameters to the function. They are only visible inside the function body and their local scope), exist only from when the function is called to when the function returns (bounded extent---note that this is different from what happens in some garbage-collected languages like Scheme), and get their initial values from the arguments to the function when it is called.

      • At the start of any block delimited by curly braces only. Such variables are exist only when the containing function is active (bounded extent) and visible only within the block (local scope again). The convention in C is generally to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first time used


    The following program demonstrate the use of global and local variables.

    #include

    int counter = 0; /* global because we are outside all blocks.*/
    int func(void);

    main()
    {
    counter++; /* global because it has not been declared within this block */
    printf("counter is %2d before the call to func\n", counter);

    func(); /* call a function. */
    printf("counter is %2d after the call to func\n", counter);
    }

    int func(void)
    {
    int counter = 10; /* local variable because it has declared within this block */
    */ printf("counter is %2d within func\n", counter);
    }


    Using static variables

    Another important feature of the variable scoping is the static variable. In a local function scope,a static variable exists only , but it does not lose its value when program execution leaves this scope. Consider the example which is given below:
    #include

    main()
    {
    Test();
    }
    function Test()
    {
    int a = 0;
    printf("a is %d within func\n", a)
    a++;
    }
    Since every time the function is called it sets a to 0 and prints "0",this function is quite useless . The a++ which increments the variable serves no purpose since as soon as the function exits then a variable disappears. The a variable is declared static to make a useful counting function which will not lose track of the current count:
    #include

    main()
    {
    Test();
    }
    function Test()
    {
    static int a = 0;
    printf("a is %d within func\n", a)
    a++;
    }


    Basic types

    There are 4 basic types of variable in C; they are: char, int, double and float
    Type name Meaning
    char The most basic unit addressable by the machine; typically a single octet. This is an integral type.
    int The most natural size of integer for the machine; typically a whole 16, 32 or 64 bit addressable word.
    float A single-precision floating point value.
    double A double-precision floating point value.



Introduction to C Programming

#vpsinghrajput

  1. In 1972, C was developed at Bell Laboratories by Dennis Ritchie.

  2. C is a simple programming language with a relatively simple to understand syntax and few keywords. 

  3. C is useless.C itself has no input/output commands, doesn't have support for strings as a fundamental data type. There is no useful math functions built in.


  4. C requires the use of libraries as C is useless by itself. This increases the complexity of the C.The use of ANSI libraries and other methods,the issue of standard libraries is resolved. 





    C Programming :: A Quick Hellow World Program

    Let's give a simple program that prints out "Hello World" to standard out. We'll call our program as hello.c.
    #include

    main() {
    printf("Hello, world!\n");
    return 0;
    }





    Explanation of The Above Code:




    • #include -This line tells the compiler to include this header file for compilation.


      • What is header file?They contain prototypes and other compiler/pre-processor directive.Prototypes are also called the basic abstract function definitions.


      • Some common header files are stdio.h,stdlib.h, unistd.h and math.h.

    • main()- This is a function, in particular it is the main block.

    • { } - These curly braces are equivalent to the stating that "block begin" and "block end".These can be used at many places,such as switch and if statement.


    • printf() - This is the actual print statement which is used in our c program fraquently.we have header file stdio.h! But what it does? How it is defined?

    • return 0-What is this? Who knows what is this
    Seems like trying to figure out all this is just way too confusing.

    • Then the return 0 statement. Seems like we are trying to give something back, and it gives the result as an integer. Maybe if we modified our main function definition: int main() ,now we are saying that our main function will be returning an integer!So,you should always explicitly declare the return type on the function.


    • Let us add #include to our includes. Let's change our original return statement to return EXIT_SUCCESS;. Now it makes sense!


    • printf always returns an int. The main pages say that printf returns the number of characters printed.It is good programming practice to check for return values. It will not only make your program more readable, but at the end it will make your programs less error prone. But we don't really need it in this particular case.So we cast the function's return to (void). fprintf,exit and fflush are the only functions where you should do this.


    • What about the documentation? We should probably document some of our code so that other people can understand what we are doing. Comments in the C89 standard are noted by this: /* */. The comment always begins with /* and ends with */.





    An Improved Code of The Above Example

    #include #include

    /* Main Function
    * Purpose: Controls our program, prints Hello, World!
    * Input: None
    * Output: Returns Exit Status
    */

    int main() {
    (void)printf("Hello, world!\n");
    return EXIT_SUCCESS;
    }


    Note:

    The KEY POINT of this whole introduction is to show you the fundamental difference between understandability and correctness. If you lose understandability in an attempt to gain correctness, you will lose at the end. Always place the understandability as a priority ABOVE correctness. If a program is more understandable in the end,the chances it can be fixed correctly will be much higher. It is recommend that you should always document your program. You stand less of a chance of screwing up your program later,if you try to make your program itself more understandable.





    The advantages of C



    In other words,for writing anything from small programs for personal amusement to complex industrial applications,C is one of a large number of high-level languages designed for general-purpose programming.
    C has many advantages:





    The C Compilation Model






    Creating, Compiling and Running Your Program

    Creating the program






    Compilation






    Running the program

    The next stage is to run your executable program.You simply type the name of the file containing it, in this case program (or a.out),to run an executable in UNIX.
    This executes your program able to print any results to the screen. At this stage there may be run-time errors, such as it may become evident that the program has produced incorrect output or division by zero.
    If so, you must return to edit your program source, and compile it again, and run it again.





    C is a High Level Language



    C is also called as a high-level language. To give a list of instructions (a computer program) to a computer,the high-level computer language is used. The native language of the computer is a stream of numbers called machine level language. As you might expect, the action resulting from a single machine language instruction is very primitive, and many thousands of them can be required to do something like substantial. A high-level language provides a set of instructions you can recombine creatively and give to the imaginary black boxe of the computer. The high-level language software will then translate these high-level instructions into the low-level machine language instructions





    Characteristics of C



    We briefly list some of C's characteristics that have lead to its popularity as a programming language and define the language. Naturally we will be studying many of these aspects throughout our tutorial.

    • Extensive use of function calls
    • Small size
    • Loose typing -- unlike PASCAL
    • Structured language
    • Low level (BitWise) programming readily available

    • Pointer implementation - extensive use of pointers for memory, array, structures and functions.
    C has now become a widely used professional language for various reasons.
    • It has high-level constructs.
    • It produces efficient programs.
    • It can handle low-level activities.
    • It can be compiled on a variety of computers.
    The main drawback of c is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of the C we can break them. Not all languages allow this. This if done carefully and properly leads to the power of C programming.





    C Program Structure

    A C program basically has the following form:
    • Preprocessor Commands

    • Function prototypes -- declare function types and variables passed to function.
    • Type definitions
    • Variables
    • Functions
    We must have a main() function
    C assumes that function returns an integer type,if the type definition is omitted. NOTE: This can be a source of the problems in a program
    /* Sample program */

    main()
    {
    printf( ``I Like C \n'' );
    exit ( 0 );
    }
    NOTE:
    1. printf is a standard C function -- called from main.
    2. C requires a semicolon at the end of the every statement.
    3. \n signifies newline. Formatted output -- more later.

    4. exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.

C Character Set

#vpsinghrajput


'C' is a case sensitive programming language, that means there is a difference in between small and capital letters( depends on thier ASCII ( American Standard Code for Information Interchange) values ) A=65 and a=97
=================================================
Alphabets --------- A , B, C, D ............(ASCII 65 to 90)
Alphabets --------- a, b, c, d ................(ASCII 97 to 122)
=================================================
Digits ------------0, 1, 2, 3, .............( ASCII 48 to 57 )
=================================================
Special characters --- # , ! ] [ " & ^ % ~ ...............
=================================================

Steps required to learn C language

#vpsinghrajput


C langauge is similar to learn english,,
To learn english, we need to follow the below steps
step: 1 ===> alphabets
step: 2 ===> words
step: 3 ===> sentence formation
step: 4 ===> paragraph ( ie., set of sentences)
step: 5 ===> essays (ie., set of paragraphs)

In the same way,, C language
step:1 ===> Alphabets, digits and special characters
step: 2 ===> Keywords, constant , variable, operators.....
step: 3 ===> Instruction / statement
step: 4 ===> Program (ie., set of instructions)
step: 5 ===> Software ( ie., set of programs)

Different types of C language files

#vpsinghrajput


When we wrote a c program, it should be saved with a extension .c (ex: sum.c)
Three main files in C language.
.c ( source file) & .bak( backup file)
.obj (object file)
.exe ( executable file (result))
=======> In the above last two files are automatically created by the compiler when our source code doesn't contain any errors.

Why 'C' Language is called Middle-Level-Lanaguage?

#vpsinghrajput


Procedure Oriented Language (or) High Level Language:
These languages have been designed to give a better programming efficieny. (ie., faster program development)
Ex:- C , C++, java etc...
Machine Oriented Language (or) Low-Level language:
These languages have been designed to give a better machine effiicieny. (ie., faster program execution).
Ex:- Machine language and Assembly language.
=
======> 'C' Stands in between these two categories . So 'C' language is Known as Middle-level-language or Intermediate language.

History of C language

#vpsinghrajput
In the year 1972 at AT'& T Bell labs "Dennis Ritchie" developed this programming language.
====> 'C' Language has its lineage from BCPL (Basic combined programming langauge) developed by Martin Richards at Cambridge University, and a Language called as 'B' written by Ken Thompson at the AT&T Bell labs.
====>Dennis Ritchie inherited the features of 'B' and 'BCPL' , added some features of his own and developed C language.
Uses of 'C' language:
'C' language was designed for implementing System Software. And it is also widely used for developing portable application Software.
System Software (O.S)
Ex: Unix ( developed using C)