0% found this document useful (0 votes)
20 views19 pages

Language Introduction

C is a procedural programming language developed by Dennis Ritchie for system programming, with features that allow low-level memory access and a clean syntax. The document outlines the structure of a C program, including header file inclusion, main method declaration, business logic, and return statements, along with examples and explanations of C standards. It also discusses the significance of the 'int' keyword, the differences between 'int main()' and 'int main(void)', and interesting facts about macros and preprocessors in C.

Uploaded by

bbaymax420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views19 pages

Language Introduction

C is a procedural programming language developed by Dennis Ritchie for system programming, with features that allow low-level memory access and a clean syntax. The document outlines the structure of a C program, including header file inclusion, main method declaration, business logic, and return statements, along with examples and explanations of C standards. It also discusses the significance of the 'int' keyword, the differences between 'int main()' and 'int main(void)', and interesting facts about macros and preprocessors in C.

Uploaded by

bbaymax420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

C Language Introduction

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and
1973. It was mainly developed as a system programming language to write operating system. The main features
of C language include low-level access to memory, simple set of keywords, and clean style, these features make
C language suitable for system programming like operating system or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from C language. Like syntax of Java,
PHP, JavaScript and many other languages is mainly based on C language. C++ is nearly a superset of C
language (There are few programs that may compile in C, but not in C++).
Beginning with C programming:
1. Structure of a C program:
After the above discussion, we can formally assess the structure of a C program. By structure, it is meant that
any program can be written in this structure only. Writing a C program in any other structure will hence lead to a
Compilation Error.
The structure of a C program is as follows:

The components of the above structure are:


1. Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C
program.
A header file is a file with extension .h which contains C function declarations and macro definitions to be
shared between several source files.
Some of C Header files:
 stddef.h – Defines several useful types and macros.
 stdint.h – Defines exact width integer types.
 stdio.h – Defines core input and output functions
 stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation
 string.h – Defines string handling functions
 math.h – Defines common mathematical functions

Syntax to include a header files in C:


#include <(header_file_name).h>
2. Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to
declare the main function is:
Syntax to Declare main method:
int main()
{}
3. Business Logic: The next part of any C program is the business logic. By business logic, it means the
variables that are to be used in the function. Hence Business Logic means declaration of the variables that
are to be used in this function. Please note that in C program, no variable can be used without being
declared. Also in a C program, the variables are to be declared before any operation in the function.
Example:
int main()
{
int a;
.
.
4. Body: Body of a function in C program, refers to the operations that are performed in the functions. It can
be anything like manipulations, searching, sorting, printing, etc.
Example:
int main()
{
int a;
printf("%d", a);
.
.
5. Return Statement: The last part in any C program is the return statement. The return statement refers to the
returning of the values from a function. This return statement and return value depend upon the return-type
of the function. For example, if the return type is void, then there will be no return statement. In any other
case, there will be a return statement and the return value will be of the type of the specified return-type.
Example:
int main()
{
int a;
printf("%d", a);
return 0;
}
2. Writing first program:
Following is first program in C
#include <stdio.h>
int main(void)
{
printf("C Programming");
return 0;
}
Let us analyze the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by preprocessor which is a
program invoked by the compiler. In a very basic term, preprocessor takes a C program and produces another C
program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In
the above example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called
header files in C. These header files generally contain declaration of functions. We need stdio.h for the function
printf() used in the program.
Line 2 [ int main(void) ] There must to be starting point from where execution of compiled C program begins.
In C, the execution typically begins with first line of main(). The void written in brackets indicates that the main
doesn‟t take any parameter. main() can be written to take parameters also. We will be covering that in future
posts.
The int written before main indicates return type of main(). The value returned by main indicates status of
program termination.
Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used in functions and
control statements like if, else, loops. All functions must start and end with curly brackets.
Line 4 [ printf(“C Programming”); ] printf() is a standard library function to print something on standard
output. The semicolon at the end of printf indicates line termination. In C, semicolon is always used to indicate
end of statement.
Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by
operating system to know termination status of your program. The value 0 typically means successful
termination.
3. How to execute the above program:
Inorder to execute the above program, we need to have a compiler to compile and run our programs.
Windows: There are many compilers available freely for compilation of C programs like Code Blocks and Dev-
CPP. We strongly recommend Code Blocks.
Linux: For Linux, gcc comes bundled with the Linux, Code Blocks can also be used with Linux.

C Programming Language Standard


The idea of this article is to introduce C standard.
What to do when a C program produces different results in two different compilers?
For example, consider the following simple C program.
void main() { }
The above program fails in gcc as the return type of main is void, but it compiles in Turbo C. How do we decide
whether it is a legitimate C program or not?
Consider the following program as another example. It produces different results in different compilers.
#include<stdio.h>
int main()
{
int i = 1;
printf("%d %d %d\n", i++, i++, i);
return 0;
}

Which compiler is right?


The answer to all such questions is C standard. In all such cases we need to see what C standard says about such
programs.
What is C standard?
The latest C standard is ISO/IEC 9899:2011, also known as C11 as the final draft was published in 2011. Before
C11, there was C99.

Can we know behavior of all programs from C standard?


C standard leaves some behavior of many C constructs as undefined and some as unspecified to simplify the
specification and allow some flexibility in implementation. For example, in C the use of any automatic variable
before it has been initialized yields undefined behavior and order of evaluations of sub-expressions is
unspecified. This specifically frees the compiler to do whatever is easiest or most efficient, should such a
program be submitted.

So what is the conclusion about above two examples?


Let us consider the first example which is “void main() {}”, the standard says following about prototype of
main().
The function called at program startup is named main. The implementation
declares no prototype for this function. It shall be defined with a return
type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names
may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
So the return type void doesn‟t follow the standard and it‟s something allowed by certain compilers.
Let us talk about second example. Note the following statement in C standard is listed under unspecified
behavior.
The order in which the function designator, arguments, and sub-expressions within the arguments are evaluated
in a function call (6.5.2.2).
What to do with programs whose behavior is undefined or unspecified in standard?
As a programmer, it is never a good idea to use programming constructs whose behavior is undefined or
unspecified; such programs should always be discouraged. The output of such programs may change with
compiler and/or machine.

int (1 sign bit + 31 data bits) keyword in C


In C programming language a most common keyword „int‟ is used to define any positive or negative integer.
But there is a difference between an integer and the numbers which can be represented with the help of the
keyword „int‟. Not every integer can be represented with the keyword „int‟. According to MinGW the size of
one „int‟ is 4 bytes which is equal to 32 bits (1 byte=8 bits). It is still a myth somewhere that „int‟ can represent
an integer or „int‟ is used to represent integers. Integer is a very vast category of numbers where as one „int‟ has
limited and exact amount of memory (size of „int‟ is 4 bytes or 32 bits) to store what is being represented by it.
An „int‟ type variable in C language is able to store only numbers till 2147483647. Beyond this number „int‟
fails to store precisely and even not correctly. „int‟ is a 32 bit data type. Whenever a number is being assigned to
an „int‟ type variable, it is first converted to its binary representation (that is in 0‟s and 1‟s) then it is kept in
memory at specific location. An „int‟ is actually 1 sign bit + 31 data bits, that is 31 bits are available for storing
the number being assigned to a „int‟ type variable and 1 bit is reserved for maintaining the sign of the number
which is either + or – . The sign is also represented by binary digits, 0 for positive sign and 1 for negative sign.
Let us understand this by an example.
Example – Consider,
int num=2147483647;
At this point first 2147483647 will be converted into its binary form which is equal to:
1111111111111111111111111111111.
1111111111111111111111111111111 is a 31 digit binary number which will be assigned to variable num‟s
right most 31 bits and the 32nd bit will have a zero(0) as the number being assigned to variable num is a positive
number. If we try to store any number greater than 2147483647 into an „int‟ type variable then we will lose
information.

Is it fine to write “void main()” or “main()” in C?


The definition
void main() { /* ... */ }

is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard
5.1.2.2.1. A conforming implementation accepts
int main() { /* ... */ }

and
int main(int argc, char* argv[]) { /* ... */ }

A conforming implementation may provide more versions of main(), but they must all have return type int. The
int returned by main() is a way for a program to return a value to “the system” that invokes it. On systems that
doesn‟t provide such a facility the return value is ignored, but that doesn‟t make “void main()” legal C++ or
legal C. Even if your compiler accepts “void main()” avoid it, or risk being considered ignorant by C
programmers.

Note also that neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to
C89 and ARM C++ ,”int” is not assumed where a type is missing in a declaration. Consequently:
#include <iostream>
main() { /* ... */ }
is an error because the return type of main() is missing.
To summarize above, it is never a good idea to use “void main()” or just “main()” as it doesn‟t confirm
standards. It may be allowed by some compilers though.

Difference between “int main()” and “int main(void)” in C?


Consider the following two definitions of main().
int main()
{
/* */
return 0;
}
and
int main(void)
{
/* */
return 0;
}
What is the difference?
Both definitions work in C also, but the second definition with void is considered technically better as it clearly
specifies that main can only be called without any parameter. In C, if a function signature doesn‟t specify any
argument, it means that the function can be called with any number of parameters or without any parameters.
For example, try to compile and run following two C programs (remember to save your files as .c). Note the
difference between two signatures of fun().
// Program 1 (Compiles and runs fine in C, but not in C++)
void fun() { }
int main(void)
{
fun(10, "GfG", "GQ");
return 0;
}
// Program 2 (Fails in compilation in both C and C++)
void fun(void) { }
int main(void)
{
fun(10, "GfG", "GQ");
return 0;
}
Unlike C, in C++, both of the above programs fails in compilation. In C++, both fun() and fun(void) are same.
So the difference is, in C, int main() can be called with any number of arguments, but int main(void) can only be
called without any argument. Although it doesn‟t make any difference most of the times, using “int main(void)”
is a recommended practice in C.
Exercise:
Predict the output of following C programs.
Question 1

#include <stdio.h>
int main()
{
static int i = 5;
if (--i){
printf("%d ", i);
main(10);
}
}
Question 2

#include <stdio.h>
int main(void)
{
static int i = 5;
if (--i){
printf("%d ", i);
main(10);
}
}

Interesting Facts about Macros and Preprocessors in C


In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by
the compiler. In a very basic term, preprocessor takes a C program and produces another C program without
any #.
Following are some interesting facts about preprocessors in C.
1) When we use include directive, the contents of included header file (after preprocessing) are copied to the
current file.
Angular brackets < and > instruct the preprocessor to look in the standard folder where all header files are
held. Double quotes “ and “ instruct the preprocessor to look into the current folder (current directory).
2) When we use define for a constant, the preprocessor produces a C program where the defined constant is
searched and matching tokens are replaced with the given expression. For example in the following
program max is defined as 100.

#include<stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}
// Output: max is 100
// Note that the max inside "" is not replaced

3) The macros can take function like arguments; the arguments are not checked for data type. For example, the
following macro INCREMENT(x) can be used for x of any data type.

#include <stdio.h>
#define INCREMENT(x) ++x
int main()
{
char *ptr = "C Programming";
int x = 10;
printf("%s ", INCREMENT(ptr));
printf("%d", INCREMENT(x));
return 0;
}
// Output: eeksQuiz 11

4) The macro arguments are not evaluated before macro expansion. For example consider the following program
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
// The macro is expended as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
// Output: 16

The previous problem can be solved using following program


#include <stdio.h>
//here, instead of writing a*a we write (a)*(b)
#define MULTIPLY(a, b) (a)*(b)
int main()
{
// The macro is expended as (2 + 3) * (3 + 5), as 5*8
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
// Output: 40

5) The tokens passed to macros can be concatenated using operator ## called Token-Pasting operator.
#include <stdio.h>
#define merge(a, b) a##b
int main()
{
printf("%d ", merge(12, 34));
}
// Output: 1234

6) A token passed to macro can be converted to a string literal by using # before it.
#include <stdio.h>
#define get(a) #a
int main()
{
// C Programming is changed to "C Programming"
printf("%s", get(C Programming));
}
// Output: C Programming

7) The macros can be written in multiple lines using „\‟. The last line doesn‟t need to have „\‟.
#include <stdio.h>
#define PRINT(i, limit) while (i < limit) \
{ \
printf("C Programming "); \
i++; \
}
int main()
{
int i = 0;
PRINT(i, 3);
return 0;
}
// Output: C Programming C Programming C Programming
8) The macros with arguments should be avoided as they cause problems sometimes. And Inline functions
should be preferred as there is type checking parameter evaluation in inline functions. From C99 onward, inline
functions are supported by C language also.
For example consider the following program. From first look the output seems to be 1, but it produces 36 as
output.
#define square(x) x*x
int main()
{
int x = 36/square(6); // Expanded as 36/6*6
printf("%d", x);
return 0;
}
// Output: 36

9) Preprocessors also support if-else directives which are typically used for conditional compilation.

int main()
{
#if VERBOSE >= 2
printf("Trace Message");
#endif
}

10) A header file may be included more than one time directly or indirectly, this leads to problems of re-
declaration of same variables/functions. To avoid this problem, directives like defined, ifdef and ifndef are used.

11) There are some standard macros which can be used to print program file (__FILE__), Date of compilation
(__DATE__), Time of compilation (__TIME__) and Line Number in C code (__LINE__)
#include <stdio.h>

int main()
{
printf("Current File :%s\n", __FILE__ );
printf("Current Date :%s\n", __DATE__ );
printf("Current Time :%s\n", __TIME__ );
printf("Line Number :%d\n", __LINE__ );
return 0;
}
/* Output:
Current File :C:\Users\GfG\Downloads\deleteBST.c
Current Date :Feb 15 2014
Current Time :07:04:25
Line Number :8 */

12) We can remove already defined macros using:


#undef MACRO_NAME

#include <stdio.h>
#define LIMIT 100
int main()
{
printf("%d",LIMIT);
//removing defined macro LIMIT
#undef LIMIT
//Next line causes error as LIMIT is not defined
printf("%d",LIMIT);
return 0;
}
//This code is contributed by Santanu
Following program is executed correctly as we have declare LIMIT as an integer variable after removing
previously defined macro LIMIT
#include <stdio.h>
#define LIMIT 1000
int main()
{
printf("%d",LIMIT);
//removing defined macro LIMIT
#undef LIMIT
//Declare LIMIT as integer again
int LIMIT=1001;
printf("\n%d",LIMIT);
return 0;
}
//This code is contributed by Santanu

/*Output is :
1000
1001
*/

Another interesting fact about macro using (#undef)


#include <stdio.h>
//div function prototype
float div(float, float);
#define div(x, y) x/y

int main()
{
//use of macro div. Note: %0.2f for taking two decimal value after point
printf("%0.2f",div(10.0,5.0));
//removing defined macro div
#undef div
//function div is called as macro definition is removed
printf("\n%0.2f",div(10.0,5.0));
return 0;
}

//div function definition


float div(float x, float y){
return y/x;
}
//This code is contributed by Santanu

/*Output is :
2.00
0.50
*/

Compiling a C program:- Behind the Scenes


C is a high level language and it needs a compiler to convert it into an executable code so that the program can
be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.
 We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
 Then compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler‟s warning messages. This option is recommended to generate better
code.
The option -o is used to specify output file name. If we do not use this option, then an output file with
name a.out is generated.
 After compilation executable is generated and we run the generated executable using below command.
$ ./filename

The details of Compilation Process


When we compile a source program, it passes through several stages pre-compiler, compiler, assembler, and
linker shown in Figure 1.6.1
The pre-compiler acts only on pre-compiler directives, i.e., statements starting with # symbol in column 1 and
modify the source program. If there is any invalid pre-compiler directive, or invalid file name the process
terminates with an appropriate error message. Compiler acts on the expanded source and generates assembly
source saved with the same file name with extension s. The assembler takes the assembly source and generates
the object file if there is no syntax error; the default file name is same as the source file name with extension o.
The linker links the unresolved function reference of object file and creates the executable code file. The
executable code file is not created if there is any unresolved function reference, and the linker terminates with an
appropriate error message. However, you can stop the process after any stage or start from any stage with
appropriate compiler option.

Header file C source file

precompiler

Expanded source

compiler

Assembly source

assembler
Library file

Object file

linker

Executable code

Diagram 1: Different phases of compilation


Compiler options to start from any phase or to stop after any stage of compilation
We can start from any phase and stop after any phase of compilation with appropriate compiler options. Let us
illustrate this by an example.
C source file example1.c
a) start from beginning and terminate after precompiler
$ gcc –E example1.c 1 > example1.i
The output of precompiler is by default displayed on the screen; to save it output redirection is used where 1 is
fd of the output file. The output file is saved with the name example1.i you can inspect the contents of
expanded source by vi editor.
b) start from compiler and terminate after compiler
$ gcc –S example1.i
When the file extension is i, the compilation process skips the precompiler and starts from compiler stage. The
compiler option –S terminates the process after compilation and saves the output file with the default name
example1.s which is the assembly source program. You can inspect the contents of assembly source by vi editor.
c) start from assembler and terminate after assembler
$ gcc –c example1.s
When the file extension is s, the compilation process will start from assembler stage. The compiler option –c
will terminate after assembly and will save the output with the default name of example1.o which is an object
file. This file is binary in nature and cannot be inspected by vi editor.
d) start from linker and generate the executable code file
$ gcc example1.o –lm
When the file extension is o the compilation process will start from the linker; libraries necessary for this
program are to be identified with –l option. In this case –lm indicates that this program requires math library. All
library files are available in the directory /usr/lib/ . However, if the library is stored in other directory that is to
be indicated by –L option. The default name of the executable code file is a.out. Any other name can be
assigned with the compiler option –o.
e) executing a program
$ ./a.out
The executable code a.out in the current directory will be executed and the output will be displayed on the
screen.

To debug a program with the debugger (gdb) you should compile it with –g option.
$ gcc –g source.c
Some options may be combined to get the effect of all those options.

What goes inside the compilation process?


Compiler converts a C program into an executable. There are four phases for a C program to become an
executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.

Let us one by one see what these intermediate files contain.


Pre-processing
This is the first phase through which source code is passed. This phase includes:
 Removal of Comments
 Expansion of Macros
 Expansion of the included files.
The preprocessed output is stored in the filename.i. Let‟s see what‟s inside filename.i: using $vi filename.i

In the above output, source file is filled with lots and lots of info, but at the end our code is preserved.
Analysis:
 printf contains now a + b rather than add(a, b) that‟s because macros have expanded.
 Comments are stripped off.
 #include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included
in our source file.

Compiling
The next step is to compile filename.i and produce an; intermediate compiled output file filename.s. This file is
in assembly level instructions. Let‟s see through this file using $vi filename.s

The snapshot shows that it is in assembly language, which assembler can understand.
Assembly
In this phase the filename.s is taken as input and turned into filename.o by assembler. This file contains
machine level instructions. At this phase, only existing code is converted into machine language, the function
calls like printf() are not resolved. Let‟s view this file using $vi filename.o

Linking
This is the final phase in which all the linking of function calls with their definitions are done. Linker knows
where all these functions are implemented. Linker does some extra work also, it adds some extra code to our
program which is required when the program starts and ends. For example, there is a code which is required for
setting up the environment like passing command line arguments. This task can be easily verified by using $size
filename.o and $size filename. Through these commands, we know that how output file increases from an
object file to an executable file. This is because of the extra code that linker adds with our program.

Note that GCC by default does dynamic linking, so printf() is dynamically linked in above program.

Benefits of C language over other programming languages


C is a middle level programming language developed by Dennis Ritchie during the early 1970s while working at
AT&T Bell Labs in USA. The objective of its development was in the context of the re-design of the UNIX
operating system to enable it to be used on multiple computers.
Earlier the language B was now used for improving the UNIX system. Being a high level language, B allowed
much faster production of code than in assembly language. Still, B suffered from drawbacks as it did not
understand data-types and did not provide the use of “structures”.
These drawbacks became the driving force for Ritchie for development of a new programming language called
C. He kept most of language B‟s syntax and added data-types and many other required changes. Eventually C
was developed during 1971-73, containing both high-level functionality and the detailed features required to
program an operating system. Hence, many of the UNIX components including UNIX kernel itself were
eventually rewritten in C.
Benefits of C language
1. As a middle level language, C combines the features of both high level and low level languages. It can be
used for low-level programming, such as scripting for drivers and kernels and it also supports functions of
high level programming languages, such as scripting for software applications etc.
2. C is a structured programming language which allows a complex program to be broken into simpler
programs called functions. It also allows free movement of data across these functions.
3. Various features of C including direct access to machine level hardware APIs, presence of C compilers,
deterministic resource use and dynamic memory allocation make C language an optimum choice for
scripting applications and drivers of embedded systems.
4. C language is case-sensitive which means lowercase and uppercase letters are treated differently.
5. C is highly portable and is used for scripting system applications which form a major part of Windows,
UNIX and Linux operating system.
6. C is a general purpose programming language and can efficiently work on enterprise applications, games,
graphics, and applications requiring calculations etc.
7. C language has a rich library which provides a number of built-in functions. It also offers dynamic
memory allocation.
8. C implements algorithms and data structures swiftly, facilitating faster computations in programs. This
has enabled the use of C in applications requiring higher degrees of calculations
like MATLAB and Mathematica.

Riding on these advantages, C became dominant and spread quickly beyond Bell Labs replacing many well-
known languages of that time, such as ALGOL, B , PL/I, FORTRAN etc. C language has become available on a
very wide range of platforms, from embedded microcontrollers to supercomputers.

The C language has formed the basis for many languages including C++, C–, C#, Objective-C, BitC, C-shell,
csh, D, Java, JavaScript, Go, Rust, Julia, Limbo, LPC, PHP, Python, Perl, Verilog, Rust, Seed7, Vala, Verilog
and many more other languages are there.

Escape Sequences in C
In C programming language, there are 256 numbers of characters in character set. The entire character set is
divided into 2 parts i.e. the ASCII characters set and the extended ASCII characters set. But apart from that,
some other characters are also there which are not the part of any characters set, known as ESCAPE characters.

List of Escape Sequences


\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\ooo octal number
\xhh hexadecimal number
\0 Null

Some coding examples of escape characters


// C program to illustrate \a escape sequence
#include <stdio.h>
int main(void)
{
printf("My mobile number ""is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
return (0);
}
Output:
My mobile number is 7873923408.
// C program to illustrate \b escape sequence
#include <stdio.h>
int main(void)
{
// \b - backspace character transfers the cursor one character back with
// or without deleting on different compilers.
printf("Hello Geeks\b\b\b\bF");
return (0);
}
Output:
The output is dependent upon compiler.

// C program to illustrate \n escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \n, which
// is a new line character.
printf("Hello\n");
printf("CProgramming");
return (0);
}
Output:
Hello
CProgramming
// C program to illustrate \t escape sequence
#include <stdio.h>
int
main(void)
{
// Here we are using \t, which is
// a horizontal tab character.
// It will provide a tab space
// between two words.
printf("Hello \t GFG");
return (0);
}
Output:
Hello GFG
The escape sequence “\t” is very frequently used in loop based pattern printing programs.

// C program to illustrate \v escape sequence


#include <stdio.h>
int main(void)
{
// Here we are using \v, which is vertical tab character.
printf("Hello friends");
printf("\v Welcome to GFG");
return (0);
}
Output:
Hello Friends
Welcome to GFG
// C program to illustrate \r escape sequence
#include <stdio.h>
int main(void)
{
// Here we are using \r, which
// is carriage return character.
printf("Hello fri \r ends");
return (0);
}
Output: (Depend upon compiler)
ends

// C program to illustrate \\(Backslash) escape sequence to print backslash.


#include <stdio.h>
int main(void)
{
// Here we are using \,It contains two escape sequence
// means \ and \n.
printf("Hello\\GFG");
return (0);
}
Output: (Depend upon compiler)
Hello\GFG
Explanation: It contains two escape sequence means it after printing the \ the compiler read the next \
as new line character i.e. \n, which print the GFG in the next line

// C program to illustrate \' escape sequence/ and \" escape sequence to


// print single quote and double quote.
#include <stdio.h>
int main(void)
{
printf("\' Hello Geeks\n");
printf("\" Hello Geeks");
return 0;
}
Output:
' Hello Geeks
" Hello Geeks
// C program to illustrate \? escape sequence
#include <stdio.h>
int main(void)
{
// Here we are using \?, which is used for the presentation of trigraph
// in the early of C programming. But now we don't have any use of it.
printf("\?\?!\n");
return 0;
}
Output:
??!

// C program to illustrate \OOO escape sequence


#include <stdio.h>
int main(void)
{
//we are using \OOO escape sequence, here each O in "OOO" is one to three octal
// digits(0....7).
char* s = "A\0725";
printf("%s", s);
return 0;
}
Output:
A:5
Explanation: Here 000 is one to three octal digits(0….7) means there must be at least one octal digit
after \ and maximum three. Here 072 is the octal notation, first it is converted to decimal notation that
is the ASCII value of char „:‟. At the place of \072 there is: and the output is A: 5.

// C program to illustrate \XHH escape sequence


#include <stdio.h>
int main(void)
{
// We are using \xhh escape sequence. Here hh is one or more hexadecimal
// digits(0....9, a...f, A...F).
char* s = "B\x4a";
printf("%s", s);
return 0;
}
Output:
BJ
Explanation: Here hh is one or more hexadecimal digits(0….9, a…f, A…F).There can be more than
one hexadecimal number after \x. Here, „\x4a‟ is a hexadecimal number and it is a single char. Firstly it
will get converted into decimal notation and it is the ASCII value of char „J‟. Therefore at the place of
\x4a, we can write J. So the output is BJ.

Line Splicing in C
While writing a program, sometimes we give comment about the working of the code in the comment
section with the help of single/double comment line. But we had never thought that if at the end of this
comment line if we use \(backslash) character then what will happen?
The answer of the above question is line Splicing. Lines terminated by a \ are spliced together with the
next line very early in the process of translation. §2.2 Phases of translation.
Actually whenever at the end of the comment line if we use \(backslash) character then it deletes the
backslash character and the preceding next line of code only from the entire program or we can say
that the ending \(backslash) makes the new line also as a comment for the compiler.
// C program to illustrate the concept of Line splicing.
#include <stdio.h>
int main()
{
// Line Splicing\
printf("Hello GFG\n");
printf("welcome");
return (0);
}
Output:
welcome
Explanation: In the above program as we can see when we use the \(backslash) character at the end of
comment line. Then the next line of code is treated as comment in the program and the output is
welcome.
C Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keyword: Keywords are pre-defined or reserved words in a programming language. Each


keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can‟t be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify text to be substituted for keywords before compilation by using C
preprocessor directives. C language supports 32 keywords which are given below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. Identifiers: Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits
with either a letter or the underscore(_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved
for special use. Once declared, you can use the identifier in later program statements to refer to
the associated value. A special kind of identifier, called a statement label, can be used in goto
statements.

There are certain rules that should be followed while naming c identifiers:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:
NAME REMARK
_A9 Valid
Temp.var Invalid as it contains special character other than the
underscore
void Invalid as it is a keyword

C program:
void main()
{
int a = 10;
}
In the above program there are 2 identifiers:
main: method name.
a: variable name.
3. Constants: Constants are also like normal variables. But, only difference is, their values cannot
be modified by the program once they are defined. Constants refer to fixed values. They are also
called as literals.
Constants may belong to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;

Types of Constants:
 Integer constants – Example: 0, 1, 1218, 12482
 Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
 Octal & Hexadecimal constants, Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10
 Character constants -Example: „a‟, „A‟, „z‟
 String constants -Example: “CProgramming”

4. Strings: Strings are nothing but an array of characters ended with a null character („\0‟).This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a
character is enclosed in single quotes in C and C++.Declarations for String:
char string[20] = {„C‟, ‟P‟, „r‟, „o‟, „g‟, „r‟, „a‟, „m‟, „m‟, ‟i‟, „n‟, „g‟,
„\0‟};
char string[20] = “CProgramming”;
char string [] = “CProgramming”;

Differences between above declarations are:


 When we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the
string value.
 When we declare char as “string[]”, memory space will be allocated as per the requirement
during execution of the program.

5. Special Symbols: The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose.[] () {}, ; * = #
 Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
 comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
 semi colon : It is an operator that essentially invokes something called an initialization list.
 asterick (*): It is used to create pointer variable.
 assignment operator: It is used to assign values.
 pre processor(#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
 Unary Operators: Those operators that require only single operand to act upon are known
as unary operators. For Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators

Ternary Operators: These operators require three operands to act upon. For Example
Conditional operator (?:).

You might also like