Pratap Das
Hey 🙏Namaskar❤️ Welcome to My Website

Learn C Programming Language in a simple way [Full Guide]

Introduction

The C Programming Language

  1.    C is a structured, high level, machine independent language.
  2.    It allows developers to develop a C code without worrying about the platform they are in, at the time of code development, because C code is portable. 
  3.    Many believe that C is the basic programming language one should be thorough to start his programming career. I will give you reasons why one should go for C before Java, C++ or C#.
  4.     One should know the basic concepts before entering the higher level of course, the same way C is the basic foundation for all languages, when one is good at it, he/she can get through the higher level languages like Java, C3 etc. very easily. Though it takes time at the end you will know that your hard work is paid-off. 
  5.     Major parts of operating systems like Windows, UNIX and Linux are still written in C. Because when it comes to performance nothing beats C. Even Device drivers are written in C.

HISTORY:

  As most high level languages even C was derived from ALGOL. ALGOL was introduced in early 1960’s and it was followed by Martin Richard’s BCPL (Basic Combined Programming Language) in 1967, and then next was Ken Thompson’s B in 1970 and here comes Dennis Ritchie’s C in 1972. It was mostly used on UNIX operating system. But later a book “The C Programming Language” by Brian Kernighan and Dennis Ritchie popularized C. The 1972 version is known as Traditional C. It was standardized in 1989 and named it C89 and later minor updates were made to it in the year 1995, 1999 and were named C95, C99, respectively.

  The significant changes incorporated into the standard are
1) Extensions to the character type to support non-English characters
2) A Boolean type
3) Extensions to the integer type
4) Inclusion of type definitions in the for statement.
5) Addition of imaginary and complex types.
6) Incorporation of the C++ style comment(double slash)

C HISTORY IMPORTANT DATES: 

LANGUAGE or Related UpdatesINTRODUCED IN YEARBYDESCRIPTION
ALGOLEarly 1960s
The root of all modern languages.
BCPL1967Martin RichardsBCPL- Basic Combined Programming Language. Used primarily for writing system software.
B1970Ken ThompsonOriginated from BCPL. Used to create early versions of UNIX
C (also called traditional C)1972Dennis RitchieDeveloped at Bell Laboratories. Evolved from ALGOL, BCPL and B
BOOK “The C Programming Language”1978Brian Kernighan and Dennis RitchieA book about the C programming Language.
C89 (Standardized)1989ANSI Adopted by ISO in December 1989
C951995
Minor changes to standard.
C991999
Few significant updates to standard and named it as C99

COMPILER AND EDITOR

    As C is a programming language, practicing the programs while learning is a very good habit, which turns out into efficient learning. Thus before entering into course let’s take a quick guide on famous editors and compilers available to create, edit and decode C program.

EDITOR:

  • Editor is the one in which we write or edit the C code. Ex: Notepad, Notepad++ , vim, gedit, edit plus etc.

COMPILER:

  • A compiler is a program that reads a program written in one language (called the source language) and translates it into an equivalent program in machine level language
  • The compiler also reports to its user the presence of errors in the source program so that user can re-edit the source program and compile it once again.
  • Some examples of C compilers are GCC, Clang, Intel C. Famous and most widely used Compiler is GCC . And we also have Turbo C, Borland C IDE’s with inbuilt compiler.

       Okay !!! Now as we came to know about editor and compiler, let’s go further into the topic. There are software’s called IDE available in market.
But what is an IDE?

For more compiler’s check out this article from about.com , and from Wikipedia.com.

How to start with Turbo C and GCC

Install Turbo C in your computer’s C Drive and follow the below shown commands to open it.

METHOD 1: Using command prompt.
Step1: Win + R ; will open a run command prompt.
Step2: Type cmd and hit Enter ; will open command prompt.
Step3: Now type cd\ and hit Enter (will takes you to root directory i.e C drive)
Step4: Type cd TC and hit Enter (Now you are in TC folder)
Step5: Type cd bin and hit Enter ( Now you are redirected to bin folder, a subfolder in tc)
Step6: Type TC and hit Enter (will open TC window now you can write edit and compile your programs, through this command you are accessing an application called TC.exe )

How to Compile a C program using GCC

  • GCC – GNU compiler collection is a GNU project which supports C , C++, Fortran, Java, Ada and Go.
  • GCC for windows is available  .
  • Well Ubuntu provides inbuilt GCC, it is not required to install it externally so I prefer to use Ubuntu, it is available for free, download Ubuntu. .
  • In Ubuntu follow below commands to write, edit and compile your programs.

Step1: Go to Dashboard.
Step2: Type Terminal
Step3: Click on Terminal
Step4: Now type vim <your filename with extension .c>  Ex. vim prog1.c (This will create a file prog1.c and opens it in a editor called vim)
Step5: Press to get into insert mode and now you can type your program here.
Step6: After typing your program press escape to get out of insert mode and type ‘:wq’ without quotesand hit enter (This will make you to come out of vim editor by saving the file)
Step7: Now type gcc <your file name with .c extension> and hit enter to compile your file.
Step8: To execute your file type ./a.out and hit enter. This will run the file

  • We are indicating file name as a.out because in gcc after compiling the C file it will store it as a.out (where as in windows it stores as .exe). Thus in linux whatever the name you use to name a file the execution file is generated as a.out only, thus same command is used for all the files.
  • Don’t have Linux? Are you using windows? But want to compile using GCC compiler?
  • There are softwares that can install GCC on windows platform MinGWCygwin.
  • Most people now days are addicted to windows environment but most industries work on linux so they search for people who is handy with linux operating sytems, so it’s better to get addicted to linux from now.

Okay here you go then, there is an IDE available for Windows environment which will work almost similar to GCC compiler. And the software is called CODEBLOCKS, it is an open source software and you can download it here .
Now as you are ready with your compiler and editor or an IDE. Let’s start our journey.

Basic Terms in C programming language

DELIMITERS:

  • Delimiters are the characters which separate the code or indicate the code in separate blocks, in C we have braces as delimiters.

{         Start of function or block
      }         End of the function or block

  • We can write one block of statements in another block of statements as shown in the below program i.e. we can nest block of statements.

Example Program: Delimiters_Example

#include<stdio.h>
int main()
{
    int a;
    a=3+4;
   printf("\n Value of a is %d",a);
 {     /* This is start of block */
    int b=6;
    printf("\nValue of b is %d\n",b);
 }     /* This is end of a block */
}

STATEMENT:

  • A C program is made of functions and in functions we have statements, statements are the instructions given by a programmer to command a compiler how the function should work.
  • In C programming language statements are executed one after the other unless we use them in loops and control statements.
  • We can write a block of statements in between braces, we will use the block of statements more commonly in chapter called control statements.  

STATEMENT TERMINATOR:

  • In C each and every statement should end up with a semicolon (  ;  ).
  • By using semi colon at the end of each and every statement we indicate compiler that the statement has ended. And that semicolon is known as Statement Terminator.
  • For example
    i=0
    sum= a + b are called Statements.
  • But each and every statement should end with a symbol semi colon `;’ , so while programming in C, the above statements should be written as shown below.
    i=0;
    sum=a+b;

    In short a Statement Terminator is a semicolon which indicates the compiler that the statement is ended.
  • NOTE: In C programming language a statement without a Statement Terminator yields error.

COMMENTS:

  • Comments are those parts of the code which are not executed.
  • So a clever programmer use comments to indicate or give some information about the code, to make him understand the code if he revisits the same code for minor modifications or upgrade after few months or years.
  • Comments can be used anywhere in a C program.
  • There are two types of comments
    i) LINE COMMENT
    ii) BLOCK COMMENT

i)LINE COMMENT:

  • The comments contained only in one line are called Line Comments.
  • Two forward slashes are used in front of the line to comment out a line `//’.
  • Probably they are not available in old compilers.

Examples:

  • //This is a line comment.
  • int i=5; //The whole line after slashes are commented out.

NOTE: Some programmers avoid using line comment instead they go for block comment.
Why?
Because, line comment was not present in older compilers. It was incorporated into C from C99 standard.

ii) BLOCK COMMENT:

  • Block comments are the comments contained in multiple lines and they begin with forward slash, asterisk /* and ended with asterisk, slash */
  • If you begin a Block Comment then you definitely have to end it, else complier think that the whole program after `/*’ as a comment and thus it is not compiled.
  • Comments cannot be nested. They might lead to errors.

Examples:

  • /*this is a block comment*/
  • Int i=5; /* This is first line.
    And this is second line. These two lines are commented out, as they are enclosed in between block comment*/

EXAMPLE PROGRAM:

/**********************************************
PROG NAME            : Addition
PROGRAMMER’S NAME    : Ramana
OPERATION            : This program prints the sum of two numbers.
DATE                : 13 July 2014
***********************************************/
#include<stdio.h>
//Below is the main function
int main()
{  
   int sum, a=5, b=6;
   sum= a + b;           /*I am adding a and b*/
   printf("\nSum is %d", sum);
//above is a printf function which print’s the sum value;
   return 0;
}   //close of main

NOTE: Comments can also be used to indicate your co-worker about the functioning of your code. And yes, it is more helpful to write comments when you are working in groups or working for large organization. In industry many programmers work together and divide their work into parts and if you are assigned to create a part of code and pass it to your fellow co-worker, you can indicate your work using comments.

STRUCTURE OF C LANGUAGE:

            Actually there is no particular structure for C programming language, but there are certain rules to follow, to avoid errors. Most of the programmer’s follow certain structure to avoid errors, so it will be good if we follow the same.

   Below is the structure followed by most of the programmers.

  • Documentation Section
  •       Preprocessor Directives Section or Linking Section
  •       Global Declaration
  •       User defined Function Declaration
  •       Main Function 

                  {
                  Local Declarations
                  statement 1;                        Body of the function main
                  statement 2;

                  }
User defined function (if required by programmer).

DOCUMENTATION SECTION:

  • Here a programmer can denote his name, so that people can know that he is the author of the program, he can also write a brief description about the program and indicate date and any further details according to his wish. But all these things are not compiled by the compiler.
  • The documentation section starts with token /* and ends with token */ (of course the block comment).
  • It is not necessary that you indicate documentation section for every program but it will be good, if you are writing many programs and interlinking them. We will come across this topic in functions where we will create our own header file.

PREPROCESSOR DIRECTIVES:

  •   Preprocessor directives start with # (hash) symbol. In this section we are going to include our header files.
  •  As we know a C program consists many functions. There are many predefined functions like printf(), scanf() which we are going to use in our programs. Where is the code written for such functions? Yes, it might be somewhere in the Library Functions.
  •  The declarations for printf() and scanf() functions are stored in a header file called Stdio.h. So if we are going to use printf() and scanf() functions in our program we have to include their respective header file stdio.h in linking section.

     SYNTAX:  #include <headerfile.h >;                ( Here headerfile indicates name of the header file we are using.
Example:
#include<stdio.h>   /* Standard input/output header file*/
#include<conio.h>   /* conio.h is not found in gcc compiler*/
#include<math.h>   /* For math functions*/
#include<string.h>   /* For string functions*/

GLOBAL DECLARATION:

  •      In C if we declare variable in one function we can’t use them in other function. So when we enter topic FUNCTIONS we might require variables which should appear in both the functions, for this kind of situations we go for global declarations.
  •      Let me give you an example if we are writing a mathematical program and we need to use a constant like π=3.14. As we can’t go for a symbol as a variable name, instead we use Pi, here in place of π and initialize it with a value as shown below.

Example Program: 


 #include<stdio.h>
int pi 3.14;
main()
{
     area= pi*r*r;
}
func 2()
{
perimeter= 2*pi*r;
}

USER DEFINED FUNCTION DECLARATION:

  In this section we declare user defined functions if any in our program.

MAIN FUNCTION:

  •      Main function is the function where execution starts. A program without a main function yields error because compilation starts from main() function.
  • Local Declaration: Declaration of variables required in that particular function.
  • Body of function: Here lies the code or operations to be performed by the function.

EXAMPLE PROGRAM:

/* PROG NAME           : Addition
PROGRAMMER’S NAME      : Ramana
OPERATION              : This program prints the sum of two numbers.
DATE                   : 13 July 2014*/
#include<stdio.h>
main()
{  
int sum, a=5, b=6;     /*   Local Declarations*/
sum= a + b;       /*I am adding a and b*/ /*statements in body*/
printf("\nSum is %d", sum);
}

USER DEFINED FUNCTION:

  •          These functions are defined by user. It depends upon user’s wish, it is not mandatory to write a user defined function.
  •          For a beginner pre-defined functions are more than enough.

Check out the below info graphic for clear understanding of structure of C programming language 

c programming language

Compilation Stages of C program

STEPS FOR EXECUTION OF C PROGRAM

– After we create our source code we have to execute it.

– To obtain the executable file there are few steps where our source program will undergo conversions till executable file is generated.

– All the below conversion takes place internally we can directly get the executable file using single command gcc filename.c, but still if one want to know how the internal conversion takes place below are the stages.

– The stages  are

  • Pre-Processor stage
  • Compiler stage
  • Assembler stage
  • Linker stage
c programming language

PRE-PROCESSOR STAGE:

– Source code is the program what we have written using an editor or an IDE. Totally source code is the C program what we have created. It has an extension of .c

– This source code is sent through pre-processor where our source code is expanded, comments are removed and Macros are replaced. 

– The respective command for this stage is

 cc -E file_name.c
– It prints the code on terminal which is obtained after pre-processing.

– To obtain the expanded code in a file the command in Linux is

cc -E file_name.c  -o file_name.i
– After above said command is executed a file file_name.i is generated in present working directory and whole code obtained after pre-processing stage is stored in this file. We can open that file and view the whole content.
(Here -o filename.i means asking pre-processor to save the content in a file filename.i. You can give any name instead.)

– At this stage following changes happen

  • Header file is expanded.
  • Comments are removed
  • Macros are replaced

– Let us consider an example program

Program:


/* This program prints hello world on standard output */
#include<stdio.h>
#define pf printf // This is a macro
int main()
{
 pf("\nHello world\n"); // This instruction prints hello world
 return 0;
}

– The content after pre-processing stage looks similar to
# 1 "stage_test.c"
# 1 "<command-line>
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "stage_test.c"
# 20 "stage_test.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 374 "/usr/include/features.h" 3 4
# 1 "/usr/include/i386-linux-gnu/sys/cdefs.h" 1 3 4
# 385 "/usr/include/i386-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/i386-linux-gnu/bits/wordsize.h" 1 3 4
# 386 "/usr/include/i386-linux-gnu/sys/cdefs.h" 2 3 4
# 375 "/usr/include/features.h" 2 3 4
# 398 "/usr/include/features.h" 3 4
# 1 "/usr/include/i386-linux-gnu/gnu/stubs.h" 1 3 4
.
.
.
.
# 21 "stage_test.c" 2
int main()
{
printf("\nHello World\n");
return 0;
}

– By watching the above content we can say that macros are replaced, comments are removed and the line #include<stdio.h> is been replaced with large content so we can say that header file is exapanded.

COMPILER STAGE:

– At compiler stage on the basis of expanded code i.e. dot i (.i) file or on the basis of our source code dot c (.c) files,a file with .s as extension is generated which consists assembly code.

– This assembly code is generated on the basis of our code i.e depending upon what functions and what structure we have used in our C program. And the generation is handled by compiler.

– To obtain the assembly code the commands we can use are

cc –S file_name.c
or
cc –S file_name.i
– assembler accept files with .i extension or .c extension

– You can also use cc –S file_name.i -o file_name.s if we want to change the obtained file name to any other specific file name.

– For example cc -S file_name.i -o file_aft_asm.s Now instead of file_name.s generated code is saved in file_aft_asm.s

 If we open up the .s file we can see all the assembly instructions thus we can say that the whole code is converted to assembly code.

– The generated code looks like

.file        "stage_test.c"
.section                .rodata
.LC0:
.string   "\nHello World"
.text
.globl     main
.type     main, @function
main:
.LFB0:
.cfi_startproc
pushl     %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl      %esp, %ebp
.cfi_def_cfa_register 5
andl       $-16, %esp
subl        $16, %esp
movl      $.LC0, (%esp)
call          puts
movl      $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size       main, .-main
.ident    "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
.section                .note.GNU-stack,"",@progbits

– By observing the code we can say that it is assembly language and hence the compiler generated assembly language for us.

ASSEMBLER STAGE:

– Assembler converts the assembly code to object code(machine code) so at assembler stage a file with .obj(windows) or .o(Linux) extension is generated.

– The commands are
cc –c file_name.c
or
cc –c file_name.i
or
cc -c file_name.s
– Orwe can also use cc –c file_name.s –o file_name.o to get the obtained file with a different name. Similar to command in compiler stage.

– We cannot see the contents of object file. The content somewhat look like below
ELF###\00\00\00\00\00\00\00\00\00#\00#\00#\00\00\00\00\00\00\00\00\00\00\00##\00\00\00\00\00\004\00\00\00\00\00(\00
\00
\00U‰åƒäðƒ
.
.
.

LINKER STAGE:

– At linker stage other object files are linked for example the library files. Library files are pre-compiled files which can be directly linked at linker stage after linker stage an executable file is generated.

– Command
gcc file_name.c
– Executing above command generates a file with name a.out which is the executable format of last compiled c-program. Everytime a new file is compiled the a.out is replaced with new executable file thus to retain the executable content we can store it in any other file by renaming it by using the similar command as we used in assembler and compiler stages.

gcc file_name.c -o file_name
– To run the executable we have to place ./ preceding to file_name
./a.out
or
./file_name
– An executable file have extension .exe in windows and it is named a.out in Linux.

– To get all the files in one shot we can use command

gcc –save-temps file_name.c -o file_name

Below files are generated using the above command
A pre-processed file                      : file_name.i
File after compiler stage              :  file_name.s
An object file                                 :  file_name.o
An executable file                         :  file_name

There are 32 keywords in C

 KEYWORDS :

– Keywords in c programming language are nothing but the fixed names which are identified by C compiler.

– C language has 32 keywords and they are mentioned below. We will learn these keywords at the time of their usage.

– We have very less keywords in C programming language but yet it is very powerful. The reason behind it is the pre-defined functions, which are mentioned in C library.

– When you write your c programming code in an editor which has an ability to identify the c keywords, then editor will represent these keywords in different color than the normal text.

– Below is an example of how the keywords in C language are represented in different color in VIM editor.

#include<stdio.h>
int main()
{
  int i;
  float b;
  return 0;
}

The 32 keywords which are identified by C compiler are:

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofvolatile
doifstaticwhile

Constants:

– Mathematically a constant is referred to value which doesn’t change. In C programming language it has a similar meaning, the value which cannot be changed during the program execution is known as constant.

– Like 5, 6, 7.0, 9.3, 3.4 are numeric constants, we also have character constants they are denoted in single quotes, for example ’a’, ‘c’, ’*’, ‘#’, etc.

– There are three types of constants,
i) Integer constants: 4, 5, 6, 0, 189, 96, all numbers without decimal point are considered as a integer constants.
ii) Real constants: 2.0, 3.4, 4.9, 0.567, 8.754, the numbers with decimal point are considered as real constants.
ii) Character constants: Alphabets and special symbols are considered as character constants ‘*’, ‘#’, ‘$’, ‘&’, ‘@’,’e’, ‘t’, ‘g’, etc.

NOTE: Character constants are stored in memory in form of their ASCII values.

Points to be noted:

– Constants are assigned to a variable. Ex. x=5.

– But a constant cannot be assigned to another constant. Ex 7=9, is completely invalid in C programming language because on left side of the assignment operator we need a variable which represents a particular memory location. Over here assignment operator acts as medium which saves the value on right side of it to a memory location represented by variable on left side of it.

– We can do all the operations on constants like addition, subtraction, etc. except the one mentioned above.

– A c program where you are using a constant but not assigning it to a variable is completely valid.


/* This program will not generate any error */

#include<stdio.h>
int main()
{
  45;
  76;

  return 0;
}

DATA TYPES IN C:

– In C programming language it is flexible to assign the amount of memory you want to allocate for a particular variable through data types, i. e, we can use these data types and allocate space in memory depending on our requirement.
–  These data types also define the type of data you want to store in that memory location, like normal integers or numbers with decimal points etc.
-In C data types  are of three types

  1. Primitive
  2. Derived
  3. User Defined

– Primitive: By using primitive datatypes we can create variable (which represents memory) which can store single value.
– Derived : The Datatypes which are derived from primitive datatypes are considered as Derived datatypes. E.g. Arrays, pointers
– User Defined: These kinds of datatypes are defined by user that is programmer. Ex: structure , Union, enum.
– Derived data types and user defined data types are explained in separate chapters.
– There are four types of primitive datatypes. They are:
i) char
ii) int
iii) float
iv) double
– The size and range of these C data types vary from compiler to compiler.
– The data types are mentioned before the variable’s name in Declaration Section.

Syntax:

<Data_type> <variable name>;– Angled brackets are used for demonstration purpose only and should not be used in your c program.

Examples:
 char c; /*c is a variable name and it is allocated 1 byte of memory of char type*/
int x; /*x is a variable name and it is allocated 4bytes(GCC) of memory of int type*/
float f; /*f is a variable name and it is allocated 4bytes of memory of float type */

– char provides 1 byte of memory and int provides 2 or 4 bytes of memory (compiler dependent), float provides 4 byte of memory and double provides 8 bytes of memory.
– char and int can be used to store integer type of variables i. e, like ……….-3,-2,-1,0,1,2,3,……
But they have their own limits as shown below
– char variable can store -128 to +127 signed values and 0 to 255 unsigned values
And a integer variable stores -2147483648 to +2147483647 (or) -32468 to +32467 depending on the compiler type, explained in below example.
Whereas float and double are used to store the values with decimal points for ex 3.48, thus float and double can be used to store measured values which require a decimal point precision.

Sizeof() operator:

– Using sizeof() operator we can know the size of the datatype for a respective compiler.

Syntax:
sizeof(<datatype>);
sizeof(<variable>); 
– Angled brackets are used for demonstration purpose only and should not be used in your c program.
– Make use of this example and find out the size of the datatypes provided by your compiler.

Program:


/*If you are using Turbo C use this code.*/

#include<stdio.h>
#include<conio.h>

int main()
{
 clrscr();
 printf("\n size of char %d", sizeof(char));
 printf("\n size of int %d", sizeof(int));
 printf("\n size of float %d", sizeof(float));
 printf("\n size of double %d", sizeof(double));
 getch();

 return 0;
}

Output:
   size of char 1
   size of int 2
   size of float 4
   size of double 8

Program:


/*If you are using GCC*/ 

#include<stdio.h>
int main()
{
 printf(" size of char: %d\n", sizeof(char));
 printf(" size of int: %d\n", sizeof(int));
 printf(" size of float: %d\n", sizeof(float));
 printf(" size of double: %d\n", sizeof(double)); 

 return 0;
}

Output:

size of char: 1
size of int: 4
size of float: 4
size of double: 8

– We can also find out the size of variable, as shown in below program.

Program:


/*Program to find out the size of variable of particular type*/ 

#include<stdio.h>
int main()
{
 int i;
 float f;
 char c;
 double d;

 printf(" size of char\t: %d\n", sizeof(c));
 printf(" size of int\t: %d\n", sizeof(i));
 printf(" size of float\t: %d\n", sizeof(f));
 printf(" size of double\t: %d\n", sizeof(d));

 return 0;
}

Output:

  size of char     : 1
  size of int      : 4
  size of float     : 4
  size of double   : 8

NOTE: Did you notice that same program when executed in different compilers they are exhibiting different values, i.e. in Turbo C compiler size of int is 2 but in GNU C Compiler size of int is 4, but all other datatypes have same amount of memory allocated. That is the reason; I was saying the integer size is compiler dependent.
– A more detailed description on the range, memory and format specifiers are given in table below.              

DATA TYPEMEMORYFORMAT SPECIFIERRANGE
GCCTC
CHAR1byte1 byte %cSigned:-128 to 127
Unsigned: 0 to 255
INT4 bytes2 bytes%dSigned:-2147483648 to 2147483647(GCC) and
-32,468 to 32467(TC)
Unsigned: 0 to 4,294,967,295(GCC) and 0 to 65,535 (TC)
FLOAT4 bytes4 bytes%f3.4E-38 to 3.4E+38
DOUBLE8 bytes8 bytes%lf1.7E-308 to 1.7E+308

Formula to calculate range of given data type
– If it is signed datatype then: -2n-1 to [2n-1-1]     where n is the no of bits allocated for the datatype.
For Unsigned datatype: 0 to 2n-1,    where n is the number of bits, and this formula is applicable to int and char datatypes only.
– Okay! Let’s use the formula for char datatype.
Char provides 1 byte i. e, 8 bits (since 1 byte = 8 bits or 1 byte = 2 nibbles)
so n=8 => for char
=> -2n-1 to 2n-1-1
=> -28-1to 28-1 -1
=> -27to 27-1
=> -128 to 128-1
=>-128 to 127
– That’s it, signed char range is -128 to 127.
– In the similar manner calculate for unsigned char and signed and unsigned int in both TC and GCC compilers.

Variables and Identifiers

IDENTIFIERS:

– Identifiers are user defined.

– The name of the variables, functions, labels and various other user- defined objects are called identifiers.

RULES TO DECLARE AN IDENTIFIER NAME:

– An identifier can be a combination of alphabets, digits and underscore provided that first character is not a digit.

– A space  cannot be included in identifier name

– As we know C is a case sensitive identifier name like var and VAR are different and also var, VAR, vAr, vaR are also different.

– A identifier name cannot be a keyword or a function
char double;  /*double is a keyword*/
int const;       /*const is a keyword*/
int return;    /*return is a keyword*/

– Some invalid identifier names are
9abc              /*cannot start with digit*/
flower vase       /*space is included which is not valid*/
1uv*u             /* special symbols are not allowed*/
India-Hyderabad   /*hyphen not allowed*/

VARIABLES:

– Mathematically variable is a value which can be altered.

– Here in C language, a variable name is a name given to a memory location to which a constant value can be assigned and can be altered.

Syntax:
<data_type> <variable list>;
<data_type> <variable1 >,<variable2>,<variable3>;

– Angled brackets are used for demonstration purpose only and should not be used in your c program.

– In C language you can declare many variables of same data type at a time by separating them with comma operator.

Note:Never forget to end the statement with semicolon else the compiler will generate an error.

– Thus the below statement
a=25;
indicates that a value 25 is placed in memory and that memory location is named as ‘a’.

Note: The name of memory location cannot be changed but the value in it can be changed during execution.

Ex:
a=25;
after  few or next statement
a=25+6;

– Here first we are storing 25 in a and again after few statements, we are storing a=25+6  i.e. 31 is stored in a which is completely possible in C programming language.

RULES TO DECLARE A VARIABLE IN C:

As variable is one of the identifier, rules to declare a variable are same as of identifier mentioned in earlier section.

– A variable name can be a combination of alphabets, digits and underscore provided that first character is not a digit.

– A space cannot be included in variable name

– As we know C is a case sensitive variable name like var and VAR are different and also var, VAR, vAr, vaR are also different.

– In C programming language a variable name cannot be a keyword or a function
char double;  /*double is a keyword*/
int const;       /*const is a keyword*/
int return;    /*return is a keyword*/

– Some invalid variable names are
9abc;                                     /*cannot start with digit*/
flower vase;                       /*space is included which is not valid*/
1uv*u;                  /* special symbols are not allowed*/
India-Hyderabad              /*hyphen not allowed*/

VARIABLE DECLARATION AND DEFINITION:

– In below mentioned example we are saying to compiler that a variable with name exists and its type is int. Thus at same time we are defining and declaring the variable a.

– Allocating memory to a variable (ex: ‘a’) but not assigning any value to that particular location such type of statements are the examples.

Ex: int a; valid
We can also declare many variables at a time like
int a,var1,sum,b;

Program:


#include<stdio.h>
extern int x;  /* declaring x but not defining it */
int main()
{
 int a; /* declaring and defining at same time.*/
} 

VARIABLE INITIALIZATION:

– Allocating memory and at the same time storing a value to that location is called initialization.

Example:
int a=5; /* We can also declare and initialization at same time
int a=4,sum=45,c=30;/*Many variables can be initialized at once*/
int 5=a;  /*  Not valid; constant cannot be assigned a value*/

Program:


/*A program to declare a variable and print the value in it */ 

#include<stdio.h>
int main()
{
 int a;  /*variable declaration*/
 printf("\nThe value in a is %d",a);

 return 0;
}

Output:
The value in a is <garbage_value>
(output is a garbage value, i.e. you might get some random value)

– In above program a memory of 4 or 2 bytes(complier dependent) is allocated and named it as ‘a’ and look at the program we are not storing any value in a.So the output of program is a garbage value.

What is GARBAGE VALUE?

– A garbage value is a value which is stored in memory by previously executed program which could be anything. So thus the result is unidentified.

Program:


/*A program to declare a variable and store a value ‘6’ in it and print the value*/

#include<stdio.h>
int main()
{
 int a; /*variable declaration*/
 a=6; /*storing constant 6 in a*/
 printf("/n The value in a is %d", a);

 return 0;
}

Output:

The value in a is 6– Here we are declaring a variable ‘a’ and storing ‘6’ in it and printing it in a new line.

Program:


/*A program to declare a variable a and store a value ‘6’at same time*/ 

#include<stdio.h>
int main()
{
 int a=6;   /* Variable initialization*/
 printf("\n The value of a is %d",a);

 return 0;
}

Output:

The value of a is 6

CONST KEYWORD:

– We can even make the variable value unchangeable throughout the program by using keyword const. Const stands for constant.

– Const can be used locally and globally.

Syntax:
const <datatype> <variable>=<value>;
– Angled brackets are used for demonstration purpose only and should not be used in your c program.

– Here initializing a variable at the time of declaration is very important.

Example:
const int a=25;//value of a is 25 and it can’t be changed
a=100;/*trying to change value of a from 25 to 100 but it is not possible; it gives an error during compilation*/

Program: (This program yields error)


#include<stdio.h>
int main()
{
 const int a=25; /* valid*/
 a=36;   /* error */

 return 0;
}

Output:

error: assignment of read-only variable ‘a’
/
*Yields error because we are assigning 36 to a constant variable a*/

The printf and the scanf (C Library Functions)

C – FUNCTIONS:

– Till now we know that keywords are the only C elements identified by compiler, then how could be the C-programming language so powerful with just 32 keywords?
-Here comes the role of functions.
– Each compiler is provided with set of pre-defined functions whose object code is present in library. And they are linked to our file at linker stage to form an executable file.

What is a function?
– A function has got set of instructions. Whenever you require a specific set of instructions to be executed multiple times in a single program we can write those instructions in a function definition and call that function every time instead of writing those lengthy instructions again and again.
– A C program is made of functions, in each and every C program there is at least one function. One such function is main(). The main() is a function which indicates the C compiler that, the program starts here.

Syntax:
int main()   /* start of main function */
{

} /* end of main function */
– There are two types of functions
i) User Defined Function: These functions are defined by user.
ii) Pre-defined or built in Function: These functions are pre-defined and the object-code for them are present in library files (and are linked at linker stage).

– Right now we are going to concentrate only on predefined functions, we will deal with user defined functions in forthcoming chapters.
– Some pre-defined functions are printf(), scanf(), getchar(), putchar(),strlen() etc. And of course, if there are predefined functions then definitely there might be definition somewhere in the files, yes, you guessed it right, in library files.
– But our compiler cannot identify a predefined function if we use it directly in our program, without indicating its respective header file.
– Let me get it to you in simple way. The code for the function is defined in library files and their declarations are present in header files, that’s the reason we indicate the required header file in each and every program depending on the functions we use.
– For example declarations for functions printf() and scanf()are present in header file called stdio.h and declaration for functions getch() and putch() are present in header file called conio.h , so whenever we are going to use printf or scanf functions in a C program we have to include header file stdio.h in Linking section.

Syntax:
#include<stdio.h>

Printf and scanf functions:

– As we discussed earlier that, whenever we write a program which includes predefined functions we include respective header files. In here we use printf() and scanf(), thus we include header file stdio.h, so in example programs below you will find stdio.h in each and every program.

Printf():

– The C library function printf prints the data you write in between inverted comma’s within the brace’s.
– It has a return value and it returns the number of characters it printed.

c programming language
c programming language

– The declaration of printf function in stdio.h is

extern int printf (const char *format, ...);
–  It’s not that important right now to know what is meant by return type or an argument. We learn them in separate chapter called FUNCTIONS. But it is better that you know how a printf is declared.

Syntax:
printf("the content you want to print",arguments_list);

EX:
printf("This is what printf prints");

Program:


/* A program which explains the usage of pre-defined function printf() */ 

#include<stdio.h>
int main()
{
 printf("\n Hello World");
 return 0;
}

Output:
Hello World

ESCAPE SEQUENCES:

– Escape sequences in C language are mostly used in printf() function to take the control to specified point.
– For example \n takes the control to new line, and \t prints a tab space.

– Some of the escape sequences are mentioned in below table.

Characters used to denoteFunction
\nNew line
\tHorizontal tab space
\0Null character, Terminates the string
\rCarriage return, returns the control to starting position of present line
\bBackspace
\vVertical tab space
\fForm feed
\aBeep sound
\’Single quote
\”Double quote
\\Backslash
%%Inserts a % symbol

NOTE: Some call them Control Characters and some call them Escape sequences

Program:


/* A program which explains the usage of printf function with escape sequence \n */

#include<stdio.h>
int main()
{
 printf("This is my first program\n");
 printf("\nThis is second line of my first program\n");

 return 0;
}

Output:
This is my first program
This is second line of my first program

Program:


/* How to print character backslash(\) using printf function */

#include<stdio.h>
int main()
{
 printf("\n We rock \m/ ");
 return 0;
}

Output:
Warning: Unknown escape sequence \m

Program:


/*Thus to print back slash we go for such type of method as shown below*/

#include<stdio.h>
int main()
{
 printf("\n We rock \\m/ ");
 return 0;
}

Output:
We rock \m/

Program:


/* Usage of quotation marks in printf*/

#include<stdio.h>
int main()
{
 printf("\n It's called "The C Programming Language"" );
 return 0;
}

Output:
Error!!

Program:


/* To avoid errors we use \" to print double quote and \' for single quote*/

#include<stdio.h>
int main()
{
 printf("\n It's called \"The C Programming Language\"");
 printf("\n You are in \'c-programminglanguage\'");

 return 0;
} 

Output:
It's called "The C Programming Language"
You are in 'c-programminglanguage'

FORMAT SPECIFIERS:

– The format specifier,  specifies the type of variable used.
– In C format specifers are used in printf and scanf functions to specify the type of variable the function is dealing with.
– Explained in below mentioned examples.

Some of the format specifiers mentioned in below table.

Format  SpecifierPrintf() (print)Scanf() (read)
%cPrints a single characterRead a character
%dPrints a decimal integerRead a signed decimal integer
%iPrints a decimal integerRead a signed integer depending upon the prefix
– a hexadecimal integer if prefix is 0x
– a signed octal if prefix is 0
– if no prefix read signed decimal integer
%uA unsigned decimal integerUnsigned decimal integer
%oUnsigned octal integerUnsigned octal integer
%xUnsigned hexadecimal using a,b,c,d,e,fRead unsigned hexadecimal integer
%XUnsigned hexadecimal using A,B,C,D,E,F
%fA floating point with 6 digits after decimal pointRead floating point number
%eFloating point in exponential formatRead floating point number
%EFloat in exponential format with E
%gFloat in %f or %e whichever is shorterFloating point number
%GFloat in %f or %E whichever is shorter
%sStringRead a string (till null character)
%%Prints % signNot applicable
%pPrints address in hexadecimal formatNot applicable

– In printf function we can also use format specifiers like %d, %c, %f etc. to print the value of a variable. As shown in below examples where first we will create a variable and store a value in it and will print the value stored.

Program:


/* Program to print a integer value which is stored in memory*/

#include<stdio.h>
int main()
{
 int i=5; 
 printf("\n The value of i is %d", i);

 return 0;
}

Output:
The value of i is 5
Program:


/* Program to print a float value which is stored in memory*/

#include<stdio.h>
int main()
{
 float f=8.934;
 printf("The value of f is %f", f);

 return 0;
}

Output:

       The value of f is 8.934000

Program:


/* Program to print a character value stored in memory*/

#include<stdio.h>
int main()
{
 char c='a';
 printf("\n The value of c is %c", c);
 printf("\nThe ascii value is %d",c);

 return 0;
}

Output:

 The value of c is a
The ascii value is 97

Program:


/* A program to print the value returned by printf */

#include<stdio.h>
int main()
{
 int x;
 x=printf("This sentence has 31 characters");
 printf("\n The above printf returned a value and the value is %d",x);

 return 0;
}

Output:
This sentence has 31 characters
The above printf returned a value and the value is 31

Scanf

– This function reads the data we provide on screen during execution of program.
Actually it reads data from standard input i.e stdin. Standard input is a stream which consist all the input values from keyboard.
– Its header file is same as printf i.e. stdio.h

Syntax:
scanf(“<list_of_format_specifers>”, <list_of_variables>);

scanf(“<formatspecifier1> <formatspecifier2>... <formatspecifier N>”, &<variable1>, &<variable2>, …. &<variable N>);

– Angled brackets are used for demonstration purpose only and should not be used in your c program
– Remember we have to indicate & (ampersand) before the variables in scanf function, when we say &x we are telling scanf() at which memory location should it store the value supplied by the user from keyboard.

Program:


/* Capture a value from console, store it, and print it */ 

#include<stdio.h>
int main()
{
 int x;
 printf("\n Enter any integer value to store in x:");
 scanf("%d", &x);
 printf("\n The value stored in x is %d", x);

 return 0;
}

Output:

Enter any integer value to store in x:2
The value stored in x is 2

Program:


/* Take a character value from console and print it.*/ 

#include<stdio.h>
int main()
{
 char x;
 printf("\n Enter any character value to store in x: ");
 scanf("%c", &x);
 printf("\n The value stored in x is %c", x);

 return 0;
}

Output:

Enter any character value to store in x: a
The value stored in x is a

Program:


/* Take any float value from console and print it.*/

#include<stdio.h>
int main()
{
 float x;
 printf("\n Enter any float value to store in x: ");
 scanf("%f", &x);
 printf("\n The value stored in x is %f", x);

 return 0;
}

Output:

Enter any float value to store in x: 8.9
The value stored in x is 8.90000

Program:


/* A Program to know ascii value of a character */

#include<stdio.h>
int main()
{
 char x;
 x='a';
 printf("\nThe ascii value of the character present in memory x is %d",x);
 printf("\n Ascii value of 'a' is %d",'a');

 return 0;
}

Output:

The ascii value of the character present in memory x is 97
Ascii value of 'a' is 97

Program:


/* A Program to know ascii value of a character; Character is fed during execution */

#include<stdio.h>
int main()
{
 char x;
 printf(" \n Enter the character of which you want to know the ascii value : ");
 scanf("%c",&x);
 printf(" \nThe ascii value of the character '%c' is %d\n",x,x);

 return 0;
} 

Output:

Enter the character, of which you want to know the ascii value : a
The ascii value of the character 'a' is 97

Operators

– An operator is a special character or a special symbol which is used to perform a specific operation on operands. And here in C programming language, operands means the constants stored in memory.

EX: i = 5 + 3; In this statement 5 and 3 are called operands and = and + are called operators. After the calculation result is stored in a memory location named i.

– Operators are classified into three types, based on the number of operands they operate on.

  • Unary Operator
  • Binary operator
  • Ternary operator

NOTE: It’s not that important that you understand the examples given in this category of operators, we will discuss them deeply in forthcoming topics.

UNARY OPERATORS:

– Unary operators are the operators which operate on single operand.
– Some unary operators change the value of the operand in the memory after each and every operation.
– Like b++, ++b, –b, b–(where b is a variable and     ++   are operators)

Program:


#include<stdio.h> /* Header file*/

int main() /* start of main function*/
{
  int a, b = 5;  /* First lets initialize memory location a and b */
  a = ++b;  /* operation*/
 printf("Value stored in a is %d",a); /* Printing the result stored in a*/

 return 0;

} /* End of main function*/

Output:
Value stored in a is 6

Some more examples

  •    a = ++b; /*Here b is incremented and the result is stored in a*/
  •    a = b++;
  •    a = –b;
  •    a = b–;

BINARY OPERATORS:

– Binary operators are the operators which operate on two operands.
– Binary operators mostly don’t change the values in memory of respective operands they are operating on.
– Examples: a+b, a-b, a*b, a/b, a%b etc.

Program:


#include<stdio.h>    /* Header file*/

int main()     /* start of main function*/
{
 int a=4, b = 5,c; /* First lets initialize a, b and c */
 c = a+b;    /* operation*/
 printf("Value stored in c is %d",c); /* Print the result stored in c*/

 return 0;
}      /* End of main function*/

Output:
Value stored in c is 9

TERNARY OPERATORS:

– Ternary operators are the operators which operate on three operands.
– Example: 5<3 ? 5 is small : 5 is big.

Program:


#include<stdio.h> /* Header file*/
int main()    /* start of main function*/
{
  5<3 ? printf("5 is small") : printf("5 is big"); /* operation*/
 return 0;
}     /* End of main function*/

Output:
                5 is big

Operator Classification based on operation:

– Above we discussed about classification of operators based on number of operands they operate on.
– Right now let us discuss about classification of operators based upon the type of operation they perform.

  • Operators are divided into
    • Arithmetic operators
    • Assignment Operator
    • Compound Assignment
    • Comparison /Relational 
    • Logical Operators
    • Conditional
    • Increment or Decrement
    • Bitwise Operators
    • Other operators(Sizeof(), Comma, Address)

ARITHMETIC OPERATORS:

– They are binary operators, because they operate on two operands.
– These are the basic operators like addition, subtraction, multiplication, division and their symbols are same as the mathematical operators ‘+’ for addition, ‘-‘ forsubtraction, ‘*’ for multiplication, ‘/’ for division but we have an operator called  modulus or percentile denoted by ‘%’ which gives out the remainder after dividing operands. And the basic syntax is

Syntax:

<first operand> <operator> <second operand>;

or you can also go for multiple operators like

<operand1> <operator> <operand2> <operator> <operand3> <operator>…..;
– Angled brackets are used for demonstration purpose only and should not be used in your c program.

Ex:

a+b /*performs addition */
a*b /*performs multiplication*/
a-b /*performs subtraction*/
a/b /*performs division returns quotient*/
a%b /*gives remainder as output*/

Ex:
if a=5,b=6
then
a+b /*adds the value in a and b and returns the results*/
a*b /* multiplies and returns the result
a-b
if a=3,b=5 then,
a/b=0 
a%b =3

– While performing division or modulus division the denominator must not be a zero.
– 3/5 is zero? why?

Explanation: Mathematically 3/5 is 0.6 but we are storing the 0.6 in integer variable so .6 is truncated and thus 0 is the result. This topic is called type casting and explained in separate chapter.

– While modulo operation if numerator is less than denominator the value returned is numerator itself.

Note: % operator cannot be used on float values like
5.0 % 8.38, it is not valid.5%7 since 5<7 output is 5

Arithmetic example program:


/*Write a program to print result of addition, subtraction, multiplication, division and modulo division of two values. */


#include<stdio.h>
int main()
{
 int a=10, b=3;
 printf ("\nThe value of a=%d and b=%d",a,b);
 printf("\n a+b=%d",a+b);
 printf("\n a-b= %d",a-b);
 printf("\n a*b=%d",a*b);
 printf("\n a/b=%d",a/b);
 printf("\n a%%b=%d",a%b); /* %% inserts a % symbol*/

  return 0;
}

Output:
The value of a=10 and b=3
a+b=13
a-b= 7
a*b=30
a/b=3
a%b=1
– We can also take the values of a and b from runtime using scanf() function as demonstrated in below example.

Program:


/*Write a program to take a and b values from runtime and perform addition, multiplication, etc. */


#include<stdio.h>
int main()
{
 int a,b;
 printf("\nEnter the value of a: ");
 scanf("%d",&a);
 printf("\nEnter the value of b: ");
 scanf("%d",&b);
 printf("\nThe value of a=%d and b=%d",a,b);
 printf("\n a+b=%d",a+b);
 printf("\n a-b= %d",a-b);
 printf("\n a*b=%d",a*b);
 printf("\n a/b=%d",a/b);
 printf("\n a%%b=%d",a%b); /* %% inserts a % symbol*/

 return 0;
}

Output:
Enter the value of a: 3
Enter the value of b: 10
The value of a=3 and b=10
a+b=13
a-b= -7
a*b=30
a/b=0
a%b=3

Assignment Operator

ASSIGNMENT OPERATOR:– The equal to symbol ‘=’ is an Assignment operator. Assignment operator assigns the value which is on its right to left.

Syntax:
<variable>=<value>; (or) <lvalue>=<rvalue>

– Angled brackets are used for demonstration purpose only and should not be used in your c program
– Thus we can use this assignment operator to assign a constant value to variable or to assign the value in one variable to other.

EX:

i) a=10/*Assigning a constant value 10 to variable a*/

ii) a=11; /*Assigning a value 11 to */
    b=a; /* After assigning a value to and then again assigning value in a to b*/
(After this operation value in b is 11 )
iii) i=10;           /*assigning a integer value to i */
     f=10.43;     /*assigning a float value to f */
     c=’A’;         /*assigning a character to variable c*/

– But remember before assigning a value to variable, the variable should be declared first and the variable data type should match the type of value you are storing in that variable, if not, wrong data is stored (type casting or data management ).

Program:


/* Write a program to assign a value to a variable and then assign the same value to another variable using the same variable.*/

#include <stdio.h>
int main()
{
 int a;
 int b;
 a=10;
 printf("\n The value in a is %d", a);
 b=a; /*Assigning the value in a to b */
 printf("\n After assigning value in a to b ",);
 printf("\n The value in b is %d", b);

 return 0;
}

Output:

The value in a is 10
After assigning value in a to b
The value in b is 10

Program:


/* Storing different type of values in respective types*/

#include<stdio.h>
int main()
{
 int i;
 float f;
 char c;
 i=10;
 f=10.43;
 c='A';
 printf("\n i= %d",i); 
 printf("\n f=%f",f);
 printf("\n c=%c",c);

 return 0;
}

Output:

i= 10
f=10.430000
c=A

WARNING: We can’t assign a value to constant like

5=6;
It is invalid in C programming language because 5 is constant not a memory location.
– We can reassign an assigned value as demonstrated in below example.

Program:


/*A program to assign a value first and then reassign the same variable and print the value*/ 

#include<stdio.h>
int main()
{
 int a;
 a=5;
 printf("\nValue in a is %d",a);
 a=10;
 printf("\nValue in a is %d", a);

 return 0; 
}

Output:

Value in a is 5
Value in a is 10

– When we do the above operation the previous value in memory is replaced with new value. We can also assign value obtain by an expression to a variable like
a=5*5*5;         It is valid. Now in a we have value 125.

– We can also assign a variable expression like

a=x+y+z;

– we can use these type of expressions when user is willing to give values for x, y, z during the program execution. As show in below program

Program:


/* Calculate the result of the expression x+y+z */

#include<stdio.h>
int main()
{
 int a, x ,y, z;
 printf ("\n Enter value of x:\t");
 scanf("%d",&x);
 printf ("\n Enter value of y:\t");
 scanf("%d",&y);
 printf("\n Enter value of z:\t");
 scanf("%d",&z);
 a=x+y+z;
 printf("\n After x+y+z the value is %d",a);

 return 0;
}

Output:

Enter value of x:   1
Enter value of y:   2
Enter value of z:   3
After x+y+z the value is 6

COMMON MISTAKES WHILE ASSIGNMENT:
TYPE CASTING IMPLICIT ASSIGNMENT:

Program:


/* Wrong data is stored due to Implicit Type cast*/

#include<stdio.h>
int main()
{
 int a;
 a=7.3;
 printf("\nx=%d",a);

 return 0;
}

Output:

x=7
– Here we have declared variable ‘a’ as a integer type and trying to store a variable of float type which is not possible; so a store’s 7 and truncates .3, so we get output as 7.

COMPOUND ASSIGNMENT:

– While assigning, if an expression contains the variable itself (on RHS) then we go for compound assignment operators.
– Like, for x=x+3 we write x+=3, both expressions perform same operation.

Syntax:

<l_value> <compound_assignment_operator> <r_value>

– Angled brackets are used for demonstration purpose only and should not be used in your c program

– They are,
    +=
    -=
    *=
    /=
    %=

– Few examples

  • x+=5; is equivalent to x=x+5;
  • x-=5; is equivalent to x=x-5;
  • x*=5; is equivalent to x=x*5;
  • x/=5; is equivalent to x=x/5;
  • x%=5; is equivalent to x=x%5;
  •  but x%=0.5 is not valid since 0.5 is float and % cannot be used for float values.

– Not only on constants but compound assignment operators can also be used on variables.

EX:
x+=y;   =>  x=x+y;
we can also use them on expressions like below
x+=5*6; is equivalent to x=x+(5*6);
x+=7*y; is equivalent to x=x+(7*y);

Program:


/*A program to add and perform other basic operations using compound assignment operators.*/

#include<stdio.h>
int main()
{ 
 int x;
 x=8;
 x=x+5;
 printf ("\n value in x is % d",x);
 x=8;
 x+=5;
 printf ("\n value in x is % d",x);
 x=8;
 x=x%5;
 printf("\n value in x %d",x);
 x=8;
 x%=5;
 printf("\n value in x %d",x);

 return 0; 
}

Output:

value in x is  13
value in x is  13
value in x 3
value in x 3

Comparison or Relational

TRUE or FALSE in C Language: In C language any value other than ’0’ is considered as true and value ‘0’ is considered as false.

COMPARISON/RELATIONAL OPERATOR:

– Greater than, greater than or equal to, less than, less than or equal to, equal to, not equal to are denoted by >, >=, <, <=, ==, != respectively and are called Relational operators.

– These operators return boolean value (true or false) i.e. 1 or 0 after the operation is performed.

Syntax:
<operand> <operator> <operand>;– Angled brackets are used for demonstration purpose only and should not be used in your c program

Examples:
1) if a=5,b=6
then,
a>b  =>  5>6   returns 0
a>b  =>  5>=6  returns 0
a<b  =>  5<6   returns 1

2) if a=5, b=5
then
a!=b => 5!=5 is false so returns 0
a==b => 5==5 is true so returns 1

– Wondered how to collect the returned value? It’s simple and it is shown below.

x=a>b;
printf("%d",x);/* it will  print value returned by a>b;*/

– we can also write the program as shown below.

printf("%d",a>b);/* it will directly print the returned value */

– Comparison and Relational operators can be used on constants, variables & expressions.

Example:
Constants:
2<5;
7.3<8.6;
(4/2)==2;
5>=4.9;

Variables:
x>=y;x!=0;
y==x;

Expressions:
((x+y+z)>5);
(x+2)==y;
x%2==0;

Program:


/*Write a program to find greatest of two numbers using relational operators.*/

#include<stdio.h>
int main()
{
 int x,y;
 printf("\n Enter x=");
 scanf("%d",&x);
 printf("\n Enter y=");
 scanf("%d",&y);
 if(x>y)
 printf("\n x is greater");
 else
 printf("\n y is greater");

 return 0; 
} 

Output:

Enter x=4
Enter y=5
y is greater

NOTE: Here in  above example we used if keyword, we will know more about it in control statements chapter, but for now, if() is a non-iterative conditional control statement used to decide which block of statements to execute depending on the condition in parenthesis.

Program:


/* Program using all the relational operators */

#include <stdio.h>
int main()
{
 int a,b;
 printf("\nEnter value of a:");
 scanf("%d",&a);
 printf("\nEnter value of b:");
 scanf("%d",&b);
 printf("a>b = %d\n", a>b);
 printf("a>=b = %d\n",a>=b);
 printf("a<b = %d\n", a<b);
 printf("a<=b = %d\n", a<=b);
 printf("a!=b = %d\n", a!=b);
 printf("a==b = %d\n", a==b);

 return 0;
} 

Output:

Enter value of a:4
Enter value of b:5
a>b = 0
a>=b = 0
a<b = 1
a<=b = 1
a!=b = 1
a==b = 0

LOGICAL OPERATORS:

– In logical operators we have
i) Logical AND
ii) Logical OR
iii) Logical NOT

– Logical NOT is a unary operator and logical AND and Logical OR are binary operators.

– We discussed this in earlier topic but let’s regain it in C programming language any value other than ‘0’ is considered as true either it may be positive or negative. For example -1 is considered as true and positive 4 is also considered as true.

LOGICAL AND:

– Logical AND operator is denoted by two ampersands &&.

– And it gives out a true i.e. value 1 when both operands are true or we can say, when both the operands are non-zero.

Syntax:
<operand1>&&<operand2>
– Angle brackets are used for demonstration purpose only and should not be used in your c program

– Logical AND operator can be used on constants, variables and expressions.

TRUTH TABLE:

Operand 1Operand 2Result
000
0Non zero0
Non zero00
Non zeroNon zero1

Constants:
5&&4 is true i.e. 1
-1&&-2 is true
-1&&2 is true
0&&1 is false i.e. 0
10&&0 is false i.e. 0

Variables:
If a=10,b=0
a&&b is false i.e 0
b&&a is also false

Expressions:
(4+5)&&(6+3) is true i.e.
if x=3,y=4 then (x+9)&&(y+2) is true
(x-x)&&3 is false because (x-x definitely yields error and 0&&3 is false)

– In AND operation if the compiler founds first operand value ‘0’ it will not go further and check second operand, it automatically returns ‘0’

Program:


/* A program to understand the operation of Logical AND */

#include <stdio.h>
int main()
{
 int a=0,b=7;

 if(a&&(b=b+1))
 {
 a=8;
 }
 
 printf("Value of a = %d",a);
 printf("Value of b = %d",b);
 
 return 0;
}

Output:

Value of a=0
Value of b=7

Explanation:
– In above program condition in if is a&&(b=b+1) .  According to our assumption when control reaches a&&(b=b+1) it will check the condition and assigns b=b+1 zero it will not go into if body and directly prints Value of a= 0, Value of b=8; But our assumption is wrong the value of b isn’t changing. This is because to reduce the load on CPU once AND operator finds the first operand as zero, it will return 0 and will not check the second operand. Because whatever the second operand might be the resultant is zero whenever first operand is zero. Check the truth table of Logical AND.

LOGICAL OR:

– Logical OR is denoted by ||.

– It gives out value 0 when both operands are 0. And rest all other conditions it gives 1.

Syntax:
<operand1>||<operand2>– Angle brackets are used for demonstration purpose only and should not be used in your c program

‘OR’ TRUTH TABLE :

Operand1Operand2Result
000
0Non-zero1
Non-zero01
Non-zeroNon-zero1

Constants:
5||4 is true
-1||-2 is true
0||1 is true
-2||0 is true
0||0 is false

Variables:
If x=30,y=0 then
x||y is true

If x=0,y=0 then
x||y is false

Expressions:
If x=3, y=4 then
(x-x)||(y-y) returns 0
0 || (x+y) returns 1

– In OR operation computer returns 1 automatically when first operand is true, it will not go further and check if second operand is true or false.

– If x=4,y=5;

(x)||(x=x+y)
– The above expression the value returned is 1, it directly returns 1 without checking second operand i.e. after the above statements the value in x is 4 but not x+y;

Program:


/* Program to analyze Logical OR operator */
#include<stdio.h>
int main()
{
 int x=4,y=5;
 printf("Value in x= %d\n",x);
 printf("%d\n",x||(x=x+y));
 printf("Value in x= %d\n",x);

 return 0;
}

Output:

Value in x= 4
1
Value in x= 4

Logical Not:

– Denoted by ‘!’.

Syntax:
!<operand>
– Angle brackets are used for demonstration purpose only and should not be used in your c program.

– This operator returns ‘0’ if operand is non-zero and returns ‘1’ if operand is ‘0’.

– It’s kind of reverses the input.

‘NOT’ TRUTH TABLE:

OPERANDRESULT
01
Non-zero0

Program


/* Write a program using Logical operators.*/

#include<stdio.h>
int main()
{
 int x,y;
 printf("\n Enter value x:\t");
 scanf("%d",&x);
 printf("\n Enter value y:\t");
 scanf("%d",&y);
 printf("Value of x&&y is %d\n",x&&y);
 printf("Value of x||y is %d\n",x||y);
 printf("Value of !x is %d\n",!x);

 return 0;
}

Output:

Enter value x:    3
Enter value y:    0
Value of x&&y is 0
Value of x||y is 1
Value of !x is 0

Conditional Operator

– Conditional operator is ternary operator i.e. it operates on three operands.

Syntax:
<conditional_expression>?<statement1>:<statement2>
– Angle brackets are used for demonstration purpose only and should not be used in your c program.

– If conditional expression is true then statement1 is executed and if false statement2 is executed.

– Conditional operators can be used in the situations like below

5>7?printf("5 is greater"):printf("7 is greater");
x>y?printf("%d is greater",x):printf("%d is greater",y);

Program:


/* A program to find greatest of two numbers */

#include<stdio.h>
int main()
{

 int x,y;
 printf("\n Enter value x:\t");
 scanf("%d",&x);
 printf("\n Enter value y:\t");
 scanf("%d",&y);
 x>y?printf("%d is greater\n",x):printf("%d is greater\n",y);

 return 0;
}

Output:

Enter value x:  56
Enter value y:  78
78 is greater

Program:


/* Write a program to find out if a number is divisible by 2 or not */

#include<stdio.h>
int main()
{
 int x;
 printf("\nEnter value x:\t");
 scanf("%d",&x);
 (x%2)?printf("%d is not divisible by 2\n",x):printf("%d is divisible by 2\n",x);
 return 0;
}

Output:

Enter value x:  5
5 is not divisible by 2

INCREMENT AND DECREMENT OPERATORS:

– Increment and decrement operators are denoted by two plus symbols or minus symbols respectively.

– Increment and decrement operators are unary operators, i.e. they operate on single operand only.

– Increment and decrement operators change the value in memory unlike other operators, which doesn’t alter the value in memory.

– They are divided into two types i) POST and  ii) PRE
PRE INCREMENT AND PRE DECREMENT: 

– Pre-increment and decrement operators operate a specific operation where the value of the variable is incremented first and then used in further calculation.

– In pre increment or decrement operators the operator ++ or –- are indicated before the operand. Like ++x, –x.

Syntax:<operator> <operand>;

– Angle brackets are used for demonstration purpose only and should not be used in your c program.

–  For understanding let us take an example
x=5;
y=++x;

–  In above statements first we are assigning a value 5 to x and then in second statement we are incrementing x value from 5 to 6 and then assigning it to y. So after the above two statements the value in x is 6 and the value in y is also 6.

Program:


/* Program to check the operation of pre increment operator*/

#include<stdio.h>
int main()
{
 int x=5,y; /*initializing x and declaring y*/
 printf("The value in x is %d\n",x); /*Printing value of x before increment */
 y=++x; /* Pre incrementing the x value and same time assigning it to y*/
 printf("After incrementing the value in x is %d and in y is %d\n",x,y); /*Printing value of x and y after increment */

 return 0;
}

Output:
The value in x is 5
After incrementing the value in x is 6 and in y is 6

– Let us consider another similar example
x=5;
y=--x;

– In above statements first we are assigning a value 5 to x and then in second statement we are decrementing x value from 5 to 4 and then assigning it to y. So after the above two statements the value in x is 4 and the value in y is also 4.

Program:


/* Program to check the operation of pre decrement operator*/

#include<stdio.h>
int main()
{
 int x=5,y; /*initializing x and declaring y*/
 printf("The value in x is %d\n",x); /*Printing value of x before decrement */
 y=--x; /* Pre decrementing the x value and same time assigning it to y*/
 printf("After decrementing the value in x is %d and in y is %d\n",x,y); /*Printing value of x and y after decrement */

 return 0;
}

Ouput:
The value in x is 5
After decrementing the value in x is 4 and in y is 4


POST INCREMENT AND PRE DECREMENT:

– Post-increment and decrement operators operate a specific operation where the value of the variable is assigned first and then incremented.

– In post increment or decrement operators the operator ++ or – are indicated after the operand. Like x++, x–.

Syntax:<operand><operator>; 

– Angle brackets are used for demonstration purpose only and should not be used in your c program

– For understanding let us take an example
x=5;
y=x++;

– In above statements first we are assigning a value 5 to x and then in second statement we are assigning the x value to y and then incrementing it to 6. So after the above two statements the value in x is 6 and the value in y is 5.

Program:


/* Program to check the operation of post increment operator*/

#include<stdio.h>
int main()
{
 int x=5,y; /*initializing x and declaring y*/
 printf("The value in x is %d\n",x); /*Printing value of x before increment */
 y=x++; /* Post incrementing the x value and same time assigning it to y*/
 printf("After incrementing the value in x is %d and in y is %d\n",x,y); /*Printing value of x and y after increment */

 return 0;
}

Output:
The value in x is 5
After incrementing the value in x is 6 and in y is 5

– Another simillar examplex=5; y=x--;

– In above statements first we are assigning a value 5 to x and then in second statement we are assigning  x value to y and then decrementing it to 4. So after the above two statements the value in x is 4 and the value in y is 5.

Program:


/* Post decrement */
#include<stdio.h>
int main()
{
 int x=5,y; /*initializing x and declaring y*/
 printf("The value in x is %d\n",x); /*Printing value of x before decrement */
 y=x--; /* Post decrementing the x value and same time assigning it to y*/
 printf("After decrementing the value in x is %d and in y is %d\n",x,y); /*Printing value of x and y after decrement */

 return 0;
}

Output:
  The value in x is 5
  After decrementing the value in x is 4 and in y is 5

Bitwise Operators

– In bitwise operators we have

  • AND    &
  • OR       |
  • XOR     ^
  • Compliment    ~
  • Right Shift      >>
  • Left shift         <<

Bitwise AND:

– Denoted by single ampersand  &, beginners get confused between bitwise AND which is denoted by & and  logical AND which is denoted by &&.

– One should be very careful while using Bitwise Operators and Logical Operators because they both perform a very different operation on operands compared to each other.

Syntax:
<operand1> & <operand2>

– Angle brackets are used for demonstration purpose only and should not be used in your c program

Truth Table:

Bit1Bit2Bit1&Bit2
000
010
100
111

– For example consider the statement 5 & 6 indicates that the AND operation is performed on individual bits of 5 and 6 after converting them to binary form.

– 5’s binary representation is 00000000 00000101 (16 bit field)
– 6’s binary representation is 00000000 00000110 (16 bit field)
So
5 – 00000000 00000101
6 – 00000000 00000110  (&)


4 – 00000000 0000010

– The bitwise operation, 5 & 6 results 4 (but it results 1 in logical AND)

Program:


/* Bitwise AND Operator */
#include<stdio.h>
int main()
{

 int a=5,b=6,c;
 c=a&b;
 printf("After AND of %d and %d the value is %d\n",a,b,c);

 return 0;
}

Output:
After AND of 5 and 6 the value is 4

Bitwise OR:

– Denoted by single vertical line , beginners get confused between bitwise OR which is denoted by | and  logical OR which is denoted by ||.

– They both perform a very different operation on operands.

Syntax:<operand1> | <operand2>

– Angle brackets are used for demonstration purpose only and should not be used in your c program

Truth Table:

Bit1Bit2Bit1|Bit2
000
011
101
111

– For example consider the statement 5 | 6 indicates that the OR operation is performed on individual bits of 5 and 6 after converting them to binary form.
– 5’s binary representation is 00000000 00000101 (16 bit field)
– 6’s binary representation is 00000000 00000110 (16 bit field)
So
5 –     00000000 00000101
6 –     00000000 00000110  |


7 –     00000000 00000111

– The bitwise operation, 5 | 6 results 7 (but it results 1 in logical OR)

Program:


/* Bitwise OR Operator */
#include<stdio.h>
int main()
{

 int a=5,b=6,c;
 c=a|b; 
 printf("After OR of %d and %d value is %d\n",a,b,c);

 return 0;
} 

Output:
After OR of 5 and 6 value is 7

Bitwise XOR:

– Denoted by single ^,

Syntax:<operand1> ^ <operand2>

– Angle brackets are used for demonstration purpose only and should not be used in your c program

Truth Table:

Bit1Bit2Bit1^Bit2
000
011
101
110

– For example consider the statement 5 ^ 6 indicate that the XOR operation is performed on individual bits of 5 and 6 after converting them to binary form.
– 5’s binary representation is 00000000 00000101 (16 bit field)
– 6’s binary representation is 00000000 00000110 (16 bit field)
So
5 –     00000000 00000101
6 –     00000000 00000110  (^)


3 –     00000000 00000011

– The bitwise operation, 5 ^ 6 results 3

Program:


/* Bitwise OR Operator */
#include<stdio.h>
int main()
{

 int a=5,b=6,c;
 c=a|b; 
 printf("After OR of %d and %d value is %d\n",a,b,c);

 return 0;
} 

Output:
After XOR of 5 and 6 is 3

COMPLIMENT OPERATOR:

– Denoted by tilde ~ and it compliments each and every bit of the operand.

Syntax:  ~<operand>

– Angle brackets are used for demonstration purpose only and should not be used in your c program

– Let us take number 33 in binary form it is denoted by 00000000 00100001
if you do ~33 we get 11111111 11011110, here in result each and every bit is complimented.

Program:


/* Compliment Operator */

#include<stdio.h>
int main()
{
 unsigned int x=33,y;
 y=~x;
 printf("After compliment value of %d is %d\n",x,y);

 return 0;
}

Output:
After compliment value of 33 is -34

LEFT SHIFT:

– Left shift denoted by << .

– They shift the bits to left and add zeros in place of them.

Syntax:(operand) << (no_of_bits_to_be_shifted);

– Parenthesis () are for readability purpose only they are not to be used in program.

– If you are left shifting x five times then you have to write x<<5 that’s it.

– For example if 5 is stored in x i.e. x=5 and now if we are left shifting 5 three times, x<<3 the operation performed by processor are as follows.
– 5 in binary 0000 0101
left shifting and adding zero’s 0010 1000 The colored bits are added by above operator after shifting the bits 3 times.

– Thus now after left shifting the value of x is 40.

Program:


#include<stdio.h>
int main()
{
 int x,y;
 printf("\n Enter your number: ");
 scanf("%d",&x;);
 printf("\n Enter the no. of bits to be shifted: ");
 scanf("%d",&y;);
 printf("\nThe value in x after left shifting %d times is %d\n",y,x<<y);

 return 0;
}

Output:
Enter your number: 5
Enter the no. of bits to be shifted: 3
The value in x after left shifting 3 times is 40

RIGHT SHIFT:

– It operates similar to left shift and denoted by >>.

Syntax:(operand)>>(count)

– Parenthesis () are for readability purpose only and should not be included in program.

– For 5>>2 steps performed by processor are
5 - 00000101
00000010 - shifting 1st time (1 is removed)
00000001 – shifting 2nd time (0 is removed)
After right shifting 5, 2 times we get 1.

Program:


/* A program to know the operation of right shift operator*/ 

#include<stdio.h>
int main()
{
 int x,y;
 printf("\n Enter your number: ");
 scanf("%d",&x;);
 printf("\n Enter the no. of bits to be shifted: ");
 scanf("%d",&y;);
 printf("The value in x after right shifting %d times is %d\n",y,x>>y);

 return 0;
}

Output:
Enter your number: 5
Enter the no. of bits to be shifted: 2
The value in x after right shifting 2 times is 1

Other Operators

– C provides size of() operator to know the size of the identifiers we use in our program.

– Size of data types may change from computer to computer depending on the type of processor the computer is using, thus for portability purposes and knowing the size ofdata types, functions and variables we use sizeof() operator.

– sizeof() operator can also be used on structures, arrays, enum (user defined datatypes) etc.

Program:


/* Program to explain sizeof operator */

#include<stdio.h>
int main()
{
 int i;
 char c;
 float f;
 double d;

 printf("\nsize of int is %d",sizeof(int));
 printf("\nsize of int is %d",sizeof(i));
 printf("\nsize of char is %d",sizeof(char));
 printf("\nsize of char is %d",sizeof(c));
 printf("\nsize of float is %d",sizeof(float));
 printf("\nsize of float is %d",sizeof(f));
 printf("\nsize of double is %d",sizeof(double));
 printf("\nsize of double is %d\n",sizeof(d));

 return 0;
}

Output:
size of int is 4
size of int is 4
size of char is 1
size of char is 1
size of float is 4
size of float is 4
size of double is 8
size of double is 8

– we can use direct datatype or related variable in sizeof() operator.

COMMA Operator:

– Denoted by comma (,) and also known as separator.

– We can separate the expressions using comma operator.

– We can declare more than one expression in a single line as shown below.

Example:
int a;
int b;
int c;
Instead we can declare them in one line as
int a,b,c;

– We can also assign the variables at same time
int a=4,b=7,c=8;

– We can also use it to decrease the no of statements as shown below
a=4;
b=5;
c=9;
y=a+b+c;

– Instead I will write all the four statements in a single line as
a=4,b=5,c=9,y=a+b+c;– In above statement first 4 is assigned to a, next 5 to b, next 9 to and the result of a+b+c to y

Program:


/* Comma Operator */
#include<stdio.h>
int main()
{
 int a,b,c,y;
 a=4,b=5,c=9,y=a+b+c;
 printf("\n The value in y is %d",y);

 return 0;
}

Ouput:
 The value in y is 18

 ADDRESS OPERATOR:

–  The address operator denoted by ampersand & is used to denote the address of a variable.

Syntax&<variable>

– Angle brackets are used for demonstration purpose only and should not be used in your c program.

– We use this address operator mostly in scanf function to supply the address of a variable to store the data.
scanf(“%d”,&x);

– In pointers concept address operator is used to get the address of the variable.  

Program:


/* Write a program to print the address of a variable. */
#include<stdio.h>
int main()
{
 int x=5;
 printf("\nThe value in x is %d",x);
 printf("\nThe address of x is %p",&x;);

 return 0;
}

Output:
The value in x is 5
The address of x is 0xbfe0e95c

– You might get some different address because address of variable is not predictable.

Type Casting

Okay !!! Till now we have learnt some programming techniques. Now let’s C how C compiler will perform operations related to datatypes.

– We can determine expression 5+6 will give a value 11 , which is an integer, but what if we have one float operand and one int operand as shown.
5.3 + 6;

– In above expression 5.3 is float and 6 is int, C first converts 6 to float that is 6.0 and then the sum is calculated.

– Now 5.3+6.0 is 11.3. Well this is called implicit type casting.

– We have two types of type casting 1) Implicit 2) Explicit

IMPLICIT TYPE CASTING:

Implicit type casting is further divided into two types
i)Direct and
ii) Assignment

DIRECT TYPECASTING:

– The expression 5.3 + 6 is an example of direct typecasting. Where compiler is converting 6 to float internally.

– Let’s have another example 7/5, where the result should be 1.4 but we get 1 because 7 and 5 are both integer values and due to implicit automatic typecasting we get the result as 1.

– Not to get such an erroneous result we convert the expression as shown below.
7.0/5 or 7/5.0 now the result is 1.4.

– Either one is true because if one is float all other variables are converted into float and the result is obtained is also float.

ASSIGNMENT TYPECASTING:

– In above example we came to know about implicit automatic typecasting(direct typecasting) but what if we have the expression as shown below
int f;
f=7.0/5 what is stored in 1.4 ?

– Well the answer is no, because the compiler converts the data type at RHS of the assignment operator to data type at the LHS of the assignment operator. Thus in above example variable f is a int type and thus in the value 1.4, .4 is truncated and   only 1 is stored in f.

Program:


/* Assignment Typecasting */ 
#include<stdio.h>
int main()
{
 int i;
 float f;
 i=7.0/5;
 f=7.0/5;

 printf("\nThe value in i is :\t%d",i);
 printf("\nThe value in f is :\t%f",f);

return 0;
}

Output:
The value in i is : 1
The value in f is : 1.400000

EXPLICIT TYPECASTING:

– We have seen that to obtain the accurate result in 7/5 we are converting one of the   variable to float type. We can also use the expression below to obtain the same result.

Example:float y;
y=(float)7/5;

– Now 1.4 is stored in y, here we are explicitly converting 7 to float thus other operand i.e. 5 is also converted to float and obtained result is stored in y.

Program:


/* Explicit type casting program */
#include<stdio.h>
main()
{
 int i;
 float f;
 i=(float)7/5;
 f=(float)7/5;

 printf("\nThe value in i is :\t%d",i);
 printf("\nThe value in f is :\t%f",f);

return 0;
}

Output:
The value in i is : 1
The value in f is : 1.400000

NOTE: Be careful with format specifiers if you are using %d to print a float value a unknown value will be printed.

Precedence Level

PRECEDENCE LEVEL:

– Till now we completed almost all the operators, so we know each and every operator’s functionality.

– But what if there are three or more operators in a single expression like 5*6+8-5/4

– If we indicate parenthesis the expression becomes
((5*6)+((8-5)/4))  then first 5*6=30 and next 8-5=3,
((30)+((3)/4))     then 3/4=0,
(30+0)             then 30+0=30
(30)               final result is 30.

– But what if we don’t denote the parenthesis for 5*6+8-5/4, what result is obtained? How the expression is calculated?

– For such type of calculations C has certain rules to follow, each and every operation is calculated based upon the precedence level or the priority level of the operators.

– The precedence chart is shown below.

– The operator with highest priority according to precedence chart is calculated first.

– If an expression has operators with same precedence then they are calculated based on associativity.

OperatorDescriptionAssociativity
( )
[ ]
.
->
++ —
Parentheses
Brackets
dot operator to access members
access members via pointer
Postfix increment/decrement
left-to-right
++ —
+ –
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Type cast
Dereference
Address operator
size of operator
right-to-left
*  /  %Multiplication/division/modulusleft-to-right
+  –Addition/subtractionleft-to-right
<<  >>Left shift, Right shift operatorleft-to-right
<  <=
>  >=
Less than/Less than or equal to
Greater than/greater than or equal to
left-to-right
==  !=Equal to/ not equal toleft-to-right
&Bitwise ANDleft-to-right
^Exclusive OR Operatorleft-to-right
|OR Operatorleft-to-right
&&Logical AND Operatorleft-to-right
| |Logical OR Operatorleft-to-right
? :Conditional Operatorright-to-left
=
+=  -=
*=  /=
%=  &=
^=  |=
<<=  >>=
Assignment Operator
Addition/subtraction (Compound)
Multiplication and division(Compound)
Modulus and bitwise AND (Compound)
Exclusive OR and inclusive OR (Compound)
Left shift and right shift (Compound)
right-to-left
,Comma operatorleft-to-right
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *