Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

C Programming Language

C is a general-purpose, high-level programming language developed in 1972 by Dennis M. Ritchie, known for its simplicity and efficiency, making it an excellent choice for beginners. It serves as a foundation for many modern programming languages and is widely used in various applications, including system programming and software development. The document also outlines the structure of a C program, its features, the compilation process, and the importance of comments and tokens in C programming.

Uploaded by

nikku0858
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C Programming Language

C is a general-purpose, high-level programming language developed in 1972 by Dennis M. Ritchie, known for its simplicity and efficiency, making it an excellent choice for beginners. It serves as a foundation for many modern programming languages and is widely used in various applications, including system programming and software development. The document also outlines the structure of a C program, its features, the compilation process, and the importance of comments and tokens in C programming.

Uploaded by

nikku0858
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

C Programming Language

What is C?
C is a general-purpose, procedural, high-level programming language used in the
development of computer software and applications, system programming, games, and
more.
 C language was developed by Dennis M. Ritchie at the Bell Telephone Laboratories
in 1972.
 It is a powerful and flexible language which was first developed for the programming of
the UNIX operating System.
 C is one of the most widely used programming languages.
C programming language is known for its simplicity and efficiency. It is the best choice
to start with programming as it gives you a foundational understanding of programming.
Why Should We Learn C?
Many later languages have borrowed syntax/features directly or indirectly from the C
language like the syntax of Java, PHP, JavaScript, and many other languages that are
mainly based on the C language. C++ is nearly a superset of C language (Only a few
programs may compile in C, but not in C++).
So, if a person learns C programming first, it will help them to learn any modern
programming language as well. Also, learning C helps to understand a lot of the
underlying architecture of the operating system like pointers, working with memory
locations, etc.

Difference Between C and C++


C++ was created to add the OOPs concept into the C language so they both have very
similar syntax with a few differences. The following are some of the main differences
between C and C++ Programming languages.
 C++ supports OOPs paradigm while C only has the procedural concept of
programming.
 C++ has exception handling capabilities. In C, we have to resolve exceptions manually.
 There are no references in C.
There are many more differences between C and C++ which are discussed
here: Difference between C and C++
Beginning with C Programming
Writing the First Program in C
The following code is one of the simplest C programs that will help us understand the
basic syntax structure of a C program.
Example:
C

#include <stdio.h>

int main() {
int a = 10;
printf("%d", a);

return 0;
}

Output

10
Structure of the C program
After the above discussion, we can formally assess the basic 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 lead to a Compilation Error. The structure of a C
program is as follows:

Components of a C Program:
1. Header Files Inclusion – Line 1 [#include <stdio.h>]
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. All lines that start with # are
processed by a preprocessor which is a program invoked by the compiler. In the above
example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files
are called header files in C.
Some of the 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 number generator,
and memory allocation
 string.h – Defines string handling functions
 math.h – Defines common mathematical functions.
2. Main Method Declaration – Line 2 [int main()]
The next part of a C program is to declare the main() function. It is the entry point of a C
program and the execution typically begins with the first line of the main(). The empty
brackets indicate that the main doesn’t take any parameter (See this for more details).
The int that was written before the main indicates the return type of main(). The value
returned by the main indicates the status of program termination. See this post for more
details on the return type.
3. Body of Main Method – Line 3 to Line 6 [enclosed in {}]
The body of a function in the C program refers to statements that are a part of that
function. It can be anything like manipulations, searching, sorting, printing, etc. A pair of
curly brackets define the body of a function. All functions must start and end with curly
brackets.
4. Statement – Line 4 [printf(“Hello World”);]
Statements are the instructions given to the compiler. In C, a statement is always
terminated by a semicolon (;). In this particular case, we use printf() function to instruct
the compiler to display “Hello World” text on the screen.
5. Return Statement – Line 5 [return 0;]
The last part of any C function is the return statement. The return statement refers to the
return values from a function. This return statement and return value depend upon the
return type of the function. The return statement in our program returns the value from
main(). The returned value may be used by an operating system to know the termination
status of your program. The value 0 typically means successful termination.
What are the Most Important Features of C Language?
Here are some of the most important features of the C language:
1. Procedural Language
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General-Purpose Language
6. Rich set of built-in Operators
7. Libraries with Rich Functions
8. Middle-Level Language
9. Portability
10. Easy to Extend
If you’re looking to explore the full potential of C, especially in working with data
structures, the C Programming Course Online with Data Structures provides a
complete guide to mastering C’s features for real-world applications.
1. Procedural Language
In a procedural language like C step by step, predefined instructions are carried out. C
program may contain more than one function to perform a particular task. New people to
programming will think that this is the only way a particular programming language works.
There are other programming paradigms as well in the programming world. Most of the
commonly used paradigm is an object-oriented programming language.
2. Fast and Efficient
Newer languages like Java, python offer more features than c programming language but
due to additional processing in these languages, their performance rate gets down
effectively. C programming language as the middle-level language provides programmers
access to direct manipulation with the computer hardware but higher-level languages do
not allow this. That’s one of the reasons C language is considered the first choice to start
learning programming languages. It’s fast because statically typed languages are faster
than dynamically typed languages.
3. Modularity
The concept of storing C programming language code in the form of libraries for further
future uses is known as modularity. This programming language can do very little on its
own most of its power is held by its libraries. C language has its own library to solve
common problems.
4. Statically Type
C programming language is a statically typed language . Meaning the type of variable is
checked at the time of compilation but not at run time. This means each time a
programmer types a program they have to mention the type of variables used.
5. General-Purpose Language
From system programming to photo editing software, the C programming language is
used in various applications. Some of the common applications where it’s used are as
follows:
 Operating systems : Windows, Linux, iOS, Android, OXS
 Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.
6. Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which are used in writing
complex or simplified C programs.
7. Libraries with Rich Functions
Robust libraries and functions in C help even a beginner coder to code with ease.
8. Middle-Level Language
C Program to Print “Hello World”
The following C program displays “Hello World” in the output screen:
C

// Simple C program to display "Hello World"

// Header file for input output functions


#include <stdio.h>

// Main function: entry point for execution


int main() {

// writing print statement to print hello world


printf("Hello World");

return 0;
}

Output

Hello World
Explanation:
 #include <stdio.h> – This line includes the standard input-output library in the
program.
 int main() – The main function where the execution of the program begins.
 printf(“Hello, World!\n”); – This function call prints “Hello, World!” followed by a new
line.
 return 0; -This statement indicates that the program ended successfully.

9. Portability
C language is lavishly portable as programs that are written in C language can run and
compile on any system with either no or small changes.
10. Easy to Extend
Programs written in C language can be extended means when a program is already
written in it then some more features and operations can be added to it.
Compiling a C Program: Behind the Scenes
The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
The C program goes through the following phases during compilation:

Compilation Process in C

Understanding the compilation process in C helps developers optimize their programs.


For a deep dive into compilation and how it relates to memory and data structures, the C
Programming Course Online with Data Structures offers a behind-the-scenes look at
compiling C programs.
How do we compile and run a C program?
We first need a compiler and a code editor to compile and run a C Program. The below
example is of an Ubuntu machine with GCC compiler.
Step 1: Creating a C Source File
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
We can write a simple hello world program and save it.
Step 2: Compiling using GCC compiler
We use the following command in the terminal for compiling our filename.c source file
$ gcc filename.c –o filename
We can pass many instructions to the GCC compiler to different tasks such as:
 The option -Wall enables all compiler’s warning messages. This option is
recommended to generate better code.
 The option -o is used to specify the output file name. If we do not use this option, then
an output file with the name a.out is generated.
If there are no errors in our C program, the executable file of the C program will be
generated.
Step 3: Executing the program
After compilation executable is generated and we run the generated executable using the
below command.
$ ./filename
The program will be executed and the output will be shown in the terminal.

What goes inside the compilation process?


A 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 the below command, we get 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.

Intermediate Files

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


1. 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.
 Conditional compilation
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, the source file is filled with lots and lots of info, but in the end, our
code is preserved.
 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 have been
expanded and included in our source file.
2. 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 $nano filename.s terminal command.

Assembly Code File

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

Binary Code

4. Linking
This is the final phase in which all the linking of function calls with their definitions is 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 that 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 how the output file
increases from an object file to an executable file. This is because of the extra code that
Linker adds to our program.

Note: GCC by default does dynamic linking, so printf() is dynamically linked in above
program. Refer this, this and this for more details on static and dynamic linking.

C Comments
The comments in C are human-readable explanations or notes in the source code of a C
program. A comment makes the program easier to read and understand. These are the
statements that are not executed by the compiler or an interpreter.
It is considered to be a good practice to document our code using comments.
When and Why to use Comments in C programming?
1. A person reading a large code will be bemused if comments are not provided about
details of the program.
2. C Comments are a way to make a code more readable by providing more descriptions.
3. C Comments can include a description of an algorithm to make code understandable.
4. C Comments can be used to prevent the execution of some parts of the code.
Types of comments in C
In C there are two types of comments in C language:
 Single-line comment
 Multi-line comment

Types of Comments in C

1. Single-line Comment in C
A single-line comment in C starts with ( // ) double forward slash. It extends till the end of
the line and we don’t need to specify its end.
Syntax of Single Line C Comment
// This is a single line comment

Example 1: C Program to illustrate single-line comment

 C

// C program to illustrate

// use of single-line comment

#include <stdio.h>

int main(void)
{

// This is a single-line comment

printf("Welcome to GeeksforGeeks");

return 0;

Output:

Welcome to GeeksforGeeks

Comment at End of Code Line


We can also create a comment that displays at the end of a line of code using a single-
line comment. But generally, it’s better to practice putting the comment before the line of
code.
Example:
 C

// C program to demonstrate commenting


after line of code

#include <stdio.h>

int main() {

// single line comment here

printf("Welcome to GeeksforGeeks");
// comment here

return 0;
}

Output

Welcome to GeeksforGeeks
2. Multi-line Comment in C
The Multi-line comment in C starts with a forward slash and asterisk ( /* ) and ends with
an asterisk and forward slash ( */ ). Any text between /* and */ is treated as a comment
and is ignored by the compiler.
It can apply comments to multiple lines in the program.

Syntax of Multi-Line C Comment

/*Comment starts
continues
continues
.
.
.
Comment ends*/

Example 2: C Program to illustrate the multi-line comment

 C

/* C program to illustrate

use of

multi-line comment */

#include <stdio.h>

int main(void)

{
/*

This is a

multi-line comment

*/

/*

This comment contains some code which

will not be executed.

printf("Code enclosed in Comment");

*/

printf("Welcome to GeeksforGeeks");

return 0;

Output:

Welcome to GeeksforGeeks

Tokens in C


A token in C can be defined as the smallest individual element of the C


programming language that is meaningful to the compiler. It is the basic
component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The 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 the 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
Note: The number of keywords may change depending on the version of C you
are using. For example, keywords present in ANSI C are 32 while in C11, it was
increased to 44. Moreover, in the latest c23, it is increased to around 54.
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables,
functions, and arrays. These are user-defined names consisting of an 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 identifier called a statement label can be
used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 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 the first 31 characters are
significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be
treated as different.
For example,
 main: method name.
 a: variable name.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables but
with the difference that their values can not be modified in the program once they are
defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;
4. C Token – 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++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’,
‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
5. C Token – Special Symbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references.
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 mark the start and end of a block of
code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
 Assignment operator(=): It is used to assign values and for logical operation
validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically
by the compiler to transform your program before actual compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Bitwise One’s Complement Operator.
6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act 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 a 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 can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that requires three operands to act upon is called the
ternary operator. Conditional Operator(?) is also called the ternary operator.
Keywords in C
In C Programming language, there are many rules so to avoid different types of errors.
One of such rule is not able to declare variable names with auto, long, etc. This is all
because these are keywords. Let us check all keywords in C language.
What are Keywords?
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program. A list of
keywords in C or reserved words in the C programming language are mentioned below:

auto break case char const continue default do

double else enum extern float for goto if


auto break case char const continue default do

int long register return short signed sizeof static

struct switch typedef union unsigned void

For a better understanding of C syntax and keyword usage, our C programming


course covers all the essential C keywords and how they fit into the structure of a C
program
auto
auto is the default storage class variable that is declared inside a function or a block. auto
variables can only be accessed within the function/block they are declared. By default,
auto variables have garbage values assigned to them. Automatic variables are also called
local variables as they are local to a function.
auto int num;
Here num is the variable of the storage class auto and its type is int. Below is the C
program to demonstrate the auto keyword:
C

// C program to demonstrate
// auto keyword
#include <stdio.h>

int printvalue()
{
auto int a = 10;
printf("%d", a);
}

// Driver code
int main()
{
printvalue();
return 0;
}

Output

10
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a
loop or a break statement. The continue statement skips to the next iteration of the loop.
Below is the C program to demonstrate break and continue in C:
C

// C program to show use


// of break and continue
#include <stdio.h>
// Driver code
int main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 2)
{
continue;
}
if (i == 6)
{
break;
}
printf("%d ", i);
}
return 0;
}
utput

1 3 4 5
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a
single variable i.e, switch variable it allows us to execute multiple operations for different
possible values of a single variable.
switch(Expression)
{
case '1': // operation 1
break;
case:'2': // operation 2
break;
default: // default statement to be executed
}
Below is the C program to demonstrate the switch case statement:
C

// C program to demonstrate
// switch case statement
#include <stdio.h>

// Driver code
int main() {
int i = 4;
switch (i) {
case 1:
printf("Case 1\n");break;
case 2:
printf("Case 2\n");break;
case 3:
printf("Case 3\n");break;
case 4:
printf("Case 4\n");break;
default:
printf("Default\n");break;
}
}

Output

Case 4
Note: it is best to add a break statement after every case so that switch statement doesn’t
continue checking the remaining cases.

Output

Case 4
Default
char
char keyword in C is used to declare a character variable in the C programming language.
char x = 'D';
Below is the C program to demonstrate the char keyword:
C

// C program to demonstrate
// char keyword
#include <stdio.h>

// Driver code
int main() {
char c = 'a';
printf("%c", c);
return 0;
}

Output

a
const
The const keyword defines a variable who’s value cannot be changed.
const int num = 10;
Below is the C program to demonstrate the const keyword:
C

// C program to demonstrate
// const keyword
#include <stdio.h>

// Driver code
int main() {
const int a = 11;
a = a + 2;
printf("%d", a);
return 0;
}
This code will produce an error because the integer a was defined as a constant and it’s
value was later on changed.
Output:
error: assignment of read-only variable 'a'
a = a + 2;
do
The do statement is used to declare a do-while loop. A do-while loop is a loop that
executes once, and then checks it’s condition to see if it should continue through the loop.
After the first iteration, it will continue to execute the code while the condition is true.
Below is the C program to demonstrate a do-while loop.
C

// C program to demonstrate
// do-while keyword
#include <stdio.h>

// Driver code
int main()
{
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);

return 0;
}

Output

1 2 3 4 5
double and float
The doubles and floats are datatypes used to declare decimal type variables. They are
similar, but doubles have 15 decimal digits, and floats only have 7.
Example:
float marks = 97.5;
double num;
Below is the C program to demonstrate double float keyword:
C

// C program to demonstrate
// double float keyword
#include <stdio.h>

// Driver code
int main() {
float f = 0.3;
double d = 10.67;
printf("Float value: %f\n", f);
printf("Double value: %f\n", d);
return 0;
}
Output

Float value: 0.300000


Double value: 10.670000
if-else
The if-else statement is used to make decisions, where if a condition is true, then it will
execute a block of code; if it isn’t true (else), then it will execute a different block of code.
if(marks == 97) {
// if marks are 97 then will execute this block of code
}
else {
// else it will execute this block of code
}
Below is the C program to demonstrate an if-else statement:
C

// C program to demonstrate
// if-else keyword
#include <stdio.h>

// Driver code
int main()
{
int a = 10;
if(a < 11)
{
printf("A is less than 11");
}
else
{
printf("A is equal to or "
"greater than 11");
}
return 0;
}

Output

A is less than 11
enum
The enum keyword is used to declare an enum (short for enumeration). An enum is a
user-defined datatype, which holds a list of user-defined integer constants. By default, the
value of each constant is it’s index (starting at zero), though this can be changed. You can
declare an object of an enum and can set it’s value to one of the constants you declared
before. Here is an example of how an enum might be used:
C

// An example program to
// demonstrate working of
// enum in C
#include<stdio.h>

// enum declaration:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

// Driver code
int main()
{
//object of the enum (week), called day
enum week day;
day = Wed;
printf("%d", day);
return 0;
}

Output

2
extern
The extern keyword is used to declare a variable or a function that has an external linkage
outside of the file declaration.
C

#include <stdio.h>

extern int a;

int main(){

printf("%d", a);

return 0;
}
for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run
a certain amount of times.
Below is the C program to demonstrate a for-loop:
C

// C program to demonstrate
// for keyword
#include <stdio.h>

// Driver code
int main()
{
for (int i = 0; i < 5; i++)
{
printf("%d ", i);
}
return 0;
}

Output

0 1 2 3 4
goto
The goto statement is used to transfer the control of the program to the given label. It is
used to jump from anywhere to anywhere within a function.
Example:
goto label;
// code
label:
Below is the C program to demonstrate the goto keyword:
C

// C program demonstrate
// goto keyword
#include <stdio.h>

// Function to print numbers


// from 1 to 10
void printNumbers() {
int n = 1;

label:
printf("%d ", n);
n++;
if (n <= 10) goto label;
}

// Driver code
int main(){
printNumbers();
return 0;
}

Output

1 2 3 4 5 6 7 8 9 10
int
int keyword is used in a type declaration to give a variable an integer type. In C, the
integer variable must have a range of at least -32768 to +32767.
Example:
int x = 10;
Below is the C program to show the int keyword:
C

// C program to demonstrate
// int keyword
#include <stdio.h>
void sum() {
int a = 10, b = 20;
int sum;
sum = a + b;
printf("%d", sum);
}

// Driver code
int main() {
sum();
return 0;
}

Output

30
short, long, signed, and unsigned
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the
memory requirement and format specifiers on the 32-bit GCC compiler.
Memory Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
4 %ld
long int 2,147,483,647

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c


Memory Format
Data Type (bytes) Range Specifier

long double 16 3.4E-4932 to 1.1E+4932 %Lf


Below is the C program to demonstrate the short, long, signed, and unsigned keywords:
C

// C program to demonstrate
// short, long, signed,
// and unsigned keyword
#include <stdio.h>

// Driver code
int main() {
// short integer
short int a = 12345;

// signed integer
signed int b = -34;

// unsigned integer
unsigned int c = 12;

// L or l is used for
// long int in C.
long int d = 99998L;

printf("Integer value with a short int data: %hd", a);


printf("\nInteger value with a signed int data: %d", b);
printf("\nInteger value with an unsigned int data: %u", c);
printf("\nInteger value with a long int data: %ld", d);
return 0;
}

Output

Integer value with a short int data: 12345


Integer value with a signed int data: -34
Integer value with an unsigned int data: 12
Integer value with a long int data: 99998
return
The return statement returns a value to where the function was called.
Example:
return x;
Below is the C program to demonstrate the return keyword:
C

// C program to demonstrate
// return keyword
#include <stdio.h>
int sum(int x, int y) {
int sum;
sum = x + y;
return sum;
}

// Driver code
int main() {
int num1 = 10;
int num2 = 20;
printf("Sum: %d",
sum(num1, num2));
return 0;
}

Output

Sum: 30
sizeof
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.
Example:
sizeof(char);
sizeof(int);
sizeof(float); in bytes.
Below is the C program to demonstrate sizeof keyword:
C

// C program to demonsstrate
// sizeof keyword
#include <stdio.h>

// Driver code
int main() {
int x = 10;
printf("%d", sizeof(x));
return 0;
}

Output

4
register
Register variables tell the compiler to store variables in the CPU register instead of
memory. Frequently used variables are kept in the CPU registers for faster access.
Example:
register char c = 's';
static
The static keyword is used to create static variables. A static variable is not limited by a
scope and can be used throughout the program. It’s value is preserved even after it’s
scope.
For Example:
static int num;
struct
The struct keyword in C programming language is used to declare a structure. A structure
is a list of variables, (they can be of different data types), which are grouped together
under one data type.
For Example:
struct Geek {
char name[50];
int num;
double var;
};
Below is the C program for the struct keyword:
C

// C program to demonstrate
// struct keyword
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
};

// Driver code
int main( ) {
// Declare Book1 of type Book
struct Books book1;

// book 1 specification
strcpy(book1.title, "C++ Programming");
strcpy(book1.author, "Bjarne Stroustrup");

// Print book details


printf("Book 1 title : %s\n", book1.title);
printf("Book 1 author : %s\n", book1.author);
return 0;
}

Output

Book 1 title : C++ Programming


Book 1 author : Bjarne Stroustrup
typedef
The typedef keyword in C programming language is used to define a data type with a new
name in the program. typedef keyword is used to make our code more readable.
For Example:
typedef long num
In this example we have changed the datatype name of “long” to “num”.
union
The union is a user-defined data type. All data members which are declared under the
union keyword share the same memory location.
Example:
union GeekforGeeks {
int x;
char s;
} obj;
Below is the C program for the union keyword:
C

#include <stdio.h>
union student {
int age;
char marks;
} s;

// Driver code
int main() {
s.age = 15;
s.marks = 56;
printf("age = %d", s.age);
printf("\nmarks = %d", s.marks);
}

Output

age = 56
marks = 56
void
The void keyword means nothing i.e, NULL value. When the function return type is used
as the void, the keyword void specifies that it has no return value.
Example:
void fun() {
// program
}
volatile
The volatile keyword is used to create volatile objects. Objects which are declared volatile
are omitted from optimization as their values can be changed by code outside the scope
of the current code at any point in time.
For Example:
const volatile marks = 98;
marks are declared constant so they can’t be changed by the program. But hardware can
change it as they are volatile objects.
Conclusion
In this article, the points we learned about the keywords are mentioned below:
 Keywords are Reserved words in C with certain meanings.
 We can’t use keywords as any element’s name.
 There are 32 keywords in C all having unique meanings.
Keywords in C – FAQs
What are keywords in C?
Keywords in C are reserved words that have certain meanings and cannot be declare as
any element’s name. For example: for is used for declaring loop and it can’t be declared
as an element’s name.
How many keywords are there in the C language?
There are 32 keywords in the C language.
What is the sizeof keyword in C?
Sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.)
in bytes.
What is the default keyword in C?
The default keyword in C is used to specify the default case for the switch statement.
What is volatile in c used for?
Volatile keywords in C are used for volatile objects.
Difference between keywords and identifiers.
Keywords are reserved words that have some meaning whereas identifiers are the name-
generated names for any variable, struct, class, object, or function in C.
C Variables
A variable in C language is the name associated with some memory location to store
data of different types. There are many types of variables in C depending on the scope,
storage class, lifetime, type of data they store, etc. A variable is the basic building block of
a C program that can be used in expressions as a substitute in place of the value it stores.
What is a variable in C?
A variable in C is a memory location with some name that helps store some form of data
and retrieves it when required. We can store different types of data in the variable and
reuse the same variable for storing some other data any number of times.
They can be viewed as the names given to the memory location so that we can refer to it
without having to memorize the memory address. The size of the variable depends upon
the data type it stores. To learn how variables interact with data structures and functions,
the C Programming Course Online with Data Structures offers in-depth explanations
and practical use cases for managing variables effectively.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
Note: C is a strongly typed language so all the variables types must be specified before
using them.

Variable Syntax Breakdown

There are 3 aspects of defining a variable:


1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the
given name and data type.When the variable is declared, an entry in symbol table is
created and memory will be allocated at the time of initialization of the variable.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it.
A defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
Note: Most of the modern C compilers declare and define the variable in single step.
Although we can declare a variable in C by using extern keyword, it is not required in most
of the cases. To know more about variable declaration and definition,
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to
the variable when creating the variable.
Example
int var = 10; // variable declaration and definition (i.e. Vairable
Initialization)
Difference between Variable Initialization and Assignment
Initialization occurs when a variable is first declared and assigned an initial value. This
usually happens during the declaration of the variable. On the other hand, assignment
involves setting or updating the value of an already declared variable, and this can
happen multiple times after the initial initialization.
Example
int a=10; //Variable initialization
a=10; //assignment

How to use variables in C?


The below example demonstrates how we can use variables in C language.
C

// C program to demonstrate the


// declaration, definition and
// initialization
#include <stdio.h>

int main()
{
// declaration with definition
int defined_var;

printf("Defined_var: %d\n", defined_var);

// assignment
defined_var = 12;

// declaration + definition + initialization


int ini_var = 25;

printf("Value of defined_var after assignment: %d\n", defined_var);


printf("Value of ini_var: %d", ini_var);

return 0;
}

Output

Defined_var: 0
Value of defined_var after assignment: 12
Value of ini_var: 25
Rules for Naming Variables in C
You can assign any name to the variable as long as it follows the following rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start with
a digit.
3. No white space is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.
C Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
1. Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its
scope is limited to the block or function in which it is declared.
Example of Local Variable in C
C

// C program to declare and print local variable inside a


// function.
#include <stdio.h>

void function()
{
int x = 10; // local variable
printf("%d", x);
}
int main() { function(); }

Output

10
In the above code, x can be used only in the scope of function(). Using it in the main
function will give an error.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of
code. Its scope is the whole program i.e. we can access the global variable anywhere in
the C program after it is declared.
Example of Global Variable in C
C

// C program to demonstrate use of global variable


#include <stdio.h>

int x = 20; // global variable

void function1() { printf("Function 1: %d\n", x); }

void function2() { printf("Function 2: %d\n", x); }

int main()
{

function1();
function2();
return 0;
}

Output

Function 1: 20
Function 2: 20
In the above code, both functions can use the global variable as global variables are
accessible by all the functions.
Note: When we have same name for local and global variable, local variable will be given
preference over the global variable by the compiler.
For accessing global variable in this case, we can use the method mention here.
3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be
defined only once in a C program and its scope depends upon the region where it is
declared (can be global or local).
The default value of static variables is zero.
Syntax of Static Variable in C
static data_type variable_name = initial_value;
As its lifetime is till the end of the program, it can retain its value for multiple function calls
as shown in the example.
Example of Static Variable in C
C

// C program to demonstrate use of static variable


#include <stdio.h>

void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}

int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}

Output

First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
In the above example, we can see that the local variable will always print the same value
whenever the function will be called whereas the static variable will print the incremented
value in each function call.
Note: Storage Classes in C is the concept that helps us to determine the scope, lifetime,
memory location, and default value (initial value) of a variable.
4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use
the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.
Syntax of Auto Variable in C
auto data_type variable_name;
or
data_type variable_name; (in local scope)
Example of auto Variable in C
C

// C program to demonstrate use of automatic variable


#include <stdio.h>

void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{

function();
return 0;
}

Output

Auto Variable: 20
In the above example, both x and y are automatic variables. The only difference is that
variable y is explicitly declared with the auto keyword.
5. External Variables in C
External variables in C can be shared between multiple C files. We can declare an
external variable using the extern keyword.
Their scope is global and they exist between multiple C files.
Syntax of Extern Variables in C
extern data_type variable_name;
Example of Extern Variable in C
----------myfile.h------------
extern int x=10; //external variable (also global)

----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", x);
}
In the above example, x is an external variable that is used in multiple C files.
6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of
the conventional storage place like RAM. Their scope is local and exists till the end of
the block or a function.
These variables are declared using the register keyword.
The default value of register variables is a garbage value.
Syntax of Register Variables in C
register data_type variable_name = initial_value;
Example of Register Variables in C
C

// C program to demonstrate the definition of register


// variable
#include <stdio.h>

int main()
{
// register variable
register int var = 22;

printf("Value of Register Variable: %d\n", var);


return 0;
}

Output

Value of Register Variable: 22


NOTE: We cannot get the address of the register variable using addressof (&) operator
because they are stored in the CPU register. The compiler will throw an error if we try to
get the address of register variable.
Constant Variable in C
Till now we have only seen the variables whose values can be modified any number of
times. But C language also provides us a way to make the value of a variable immutable.
We can do that by defining the variable as constant.
A constant variable in C is a read-only variable whose value cannot be modified once it
is defined. We can declare a constant variable using the const keyword.
Syntax of Const Variable in C
const data_type variable_name = value;
Note: We have to always initialize the const variable at the definition as we cannot modify
its value after defining.
Example of Const Variable in C
C

// C Program to Demonstrate constant variable


#include <stdio.h>

int main()
{
// variable
int not_constant;

// constant variable;
const int constant = 20;

// changing values
not_constant = 40;
constant = 22;

return 0;
}

Output

FAQs on C Variables
Q1. What is the difference between variable declaration and definition in C?
Ans:
In variable declaration, only the name and type of the variable is specified but no memory
is allocated to the variable.
In variable definition, the memory is also allocated to the declared variable.
Q2. What is the variable’s scope?
Ans:
The scope of a variable is the region in which the variable exists and it is valid to perform
operations on it. Beyond the scope of the variable, we cannot access it and it is said to be
out of scope.

Constants in C
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program. The type of constant can be an integer constant, a
floating pointer constant, a string constant, or a character constant. In C language,
the const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define
constants in C, types of constants in C, their properties and the difference between literals
and constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is
declared in the program. We can not make any change in the value of the constant
variables after they are defined. If you’re interested in understanding how constants can
be integrated with various data structures, the C Programming Course Online with Data
Structures provides detailed explanations and use cases.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
const data_type var_name = value;

Example of Constants in C
C

// C program to illustrate constant variable definition


#include <stdio.h>

int main()
{

// defining integer constant using const keyword


const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",


int_const);
printf("Printing value of Character Constant: %c\n",
char_const);
printf("Printing value of Float Constant: %f",
float_const);

return 0;
}

Output

Printing value of Integer Constant: 25


Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we won’t be able
to change it. The following image describes examples of incorrect and correct variable
definitions.

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list
of the types of constants
 Integer Constant
 Character Constant
 Floating Point Constant
 Double Precision Floating Point Constant
 Array Constant
 Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are
as follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration. Otherwise, it
will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized
only once in the whole program. After that, we cannot modify the value stored inside that
variable.
C

// C Program to demonstrate the behaviour of constant


// variable
#include <stdio.h>

int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;

printf("Value of var: %d", var);


return 0;
}

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Difference Between Constants and Literals
The constant and literals are often confused as the same. But in C language, they are
different entities and have different semantics. The following table lists the differences
between the constants and literals in C:
Constant Literals

Constants are variables that cannot Literals are the fixed values that
be modified once declared. define themselves.

Constants are defined by using the They themselves are the values that
const keyword in C. They store are assigned to the variables or
literal values in themselves. constants.

We can determine the address of We cannot determine the address of


constants. a literal except string literal.

They are lvalues. They are rvalues.


Constant Literals

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor


We can also define a constant in C using #define preprocessor . The constants defined
using #define are macros that behave like a constant. These constants are not handled by
the compiler, they are handled by the preprocessor and are replaced by their value before
compilation.
#define const_name value
Example of Constant Macro
C

// C Program to define a constant using #define


#include <stdio.h>
#define pi 3.14

int main()
{

printf("The value of pi: %.2f", pi);


return 0;
}

Output

The value of pi: 3.14


Note: This method for defining constant is not preferred as it may introduce bugs and
make the code difficult to maintain.
FAQs on C Constants
Q1. Define C Constants.
Answer:
Constants in C are the immutable variables whose values cannot be modified once they
are declared in the C program.
Q2. What is the use of the const keyword?’
Answer:
The const keyword is the qualifier that is used to declare the constant variable in C
language.
Q3. Can we initialize the constant variable after the declaration?
Answer:
No, we cannot initialize the constant variable once it is declared.
Q4. What is the right way to declare the constant in C?
Answer:
The right way to declare a constant in C is to always initialize the constant variable when
we declare.
Q5. What is the difference between constant defined using const qualifier and
#define?
Answer:
The following table list the differences between the constants defined using const qualifier
and #define in C:
Constants using const Constants using #define

They are the variables that are They are the macros that are replaced
immutable by their value.

They are handled by the compiler. They are handled by the preprocessor.

Syntax: const type name = value; Syntax: #define name value

Q6. Is there any way to change the value of a constant variable in C?


Answer:
Yes, we can take advantage of the loophole created by pointers to change the value of a
variable declared as a constant in C. The below C program demonstrates how to do it.
C

// C Program to change the value of a constant variable


#include <stdio.h>

int main()
{
// defining an integer constant
const int var = 10;

printf("Initial Value of Constant: %d\n", var);

// defining a pointer to that const variable


int* ptr
= (int*)&var; // explicit cast to remove constness
// changing value
*ptr = 500;

printf("Final Value of Constant: %d\n", var);


printf("Accessing through pointer: %d\n", *ptr);
return 0;
}

Output

Initial Value of Constant: 10


Final Value of Constant: 500
Accessing through pointer: 500
Related Article – Const Qualifier in C
Data Types in C
Last Updated : 11 Oct, 2024



Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc. Each data
type requires different amounts of memory and has some specific operations
which can be performed over it.
The data types in C can be classified as follows:
Types Description Data Types

Primitive data types are the most basic data types that
Primitive Data
are used for representing simple values such as int, char, float,
Types double, void
integers, float, characters, etc.

The data types that are derived from the primitive or


Derived Types built-in datatypes are referred to as Derived Data array, pointers,
Types. function

User Defined The user-defined data types are defined by the user structure,
Data Types himself. union, enum
Understanding C’s data types is critical for writing efficient programs. If you’re
interested in how data types interact with different data structures, the C
Programming Course Online with Data Structures covers everything from
basic types to more complex structures in C programming.
The following are some main primitive data types in C:
Table of Content
 Integer Data Type
 Character Data Type
 Float Data Type
 Double Data Type
 Void Data Type
Integer Data Type
The integer datatype in C is used to store the integer numbers (any number
including positive, negative and zero without decimal part). Octal values,
hexadecimal values, and decimal values can be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;
The integer data type can also be used as
1. unsigned int: Unsigned int data type in C is used to store the data values
from zero to positive numbers but it can’t store negative values like signed
int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values
from -32,768 to 32,767.
3. long int: Larger version of the int datatype so can store values greater than
int.
4. unsigned short int: Similar in relationship with short int as unsigned int
with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof
operator to check the actual size of any data type.
Example of int
C

// C program to print Integer data types.


#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

printf("Integer value with positive data: %d\n", a);


printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);

return 0;
}
Output

Integer value with positive data: 9


Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Character Data Type
Character data type allows its variable to store only a single character. The size
of the character is 1 byte. It is the most basic data type in C. It stores a single
character and requires a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
Example of char
C

// C program to print Integer data types.


#include <stdio.h>

int main()
{
char a = 'a';
char c;

printf("Value of a: %c\n", a);

a++;
printf("Value of a after increment is: %c\n", a);

// c is assigned ASCII values


// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf("Value of c: %c", c);

return 0;
}

Output

Value of a: a
Value of a after increment is: b
Value of c: c
Float Data Type
In C programming float data type is used to store floating-point values. Float in
C is used to store decimal and exponential values. It is used to store decimal
numbers (numbers with floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Example of Float
C

// C Program to demonstrate use


// of Floating types
#include <stdio.h>

int main()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}

Output

9.000000
2.500000
0.000200
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating
point values) with double precision. It is used to define numeric values which
hold numbers with decimal values in C.
The double data type is basically a precision sort of data type that is capable of
holding 64 bits of decimal numbers or floating points. Since double has more
precision as compared to that float then it is much more obvious that it occupies
twice the memory occupied by the floating-point type. It can easily
accommodate about 16 to 17 digits after or before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using
the double keyword:
double var_name;
Example of Double
C

// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}

Output

123123123.000000
12.293123
2312312312.123123
Void Data Type
The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller. It has no values and no operations. It is used
to represent nothing. Void is used in multiple ways as function return type,
function arguments as void, and pointers to void.
Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.
int print(void);
// memory allocation function which
// returns a pointer to void.
void *malloc (size_t size);
Example of Void
C
// C program to demonstrate
// use of void pointers
#include <stdio.h>

int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}

Output

30
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so
we cannot define the universal size of the data types. For that, the C language
provides the sizeof() operator to check the size of the data types.
Example
C

// C Program to print size of


// different data type in C
#include <stdio.h>

int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n", size_of_int);


printf("The size of char data type : %d\n",
size_of_char);
printf("The size of float data type : %d\n",
size_of_float);
printf("The size of double data type : %d",
size_of_double);

return 0;
}

Output

The size of int data type : 4


The size of char data type : 1
The size of float data type : 4
The size of double data type : 8
Different data types also have different ranges up to which they can store
numbers. These ranges may vary from compiler to compiler. Below is a list of
ranges along with the memory requirement and format specifiers on the 32-bit
GCC compiler.
Data Type Size (bytes) Range Format Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf


Data Type Size (bytes) Range Format Specifier

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Note: The long, short, signed and unsigned are datatype modifier that can
be used with some primitive data types to change the size or length of the
datatype.
To check your knowledge of data types in C, go through the Quiz on Data
Types.

Example of int
C

// C program to print Integer data types.


#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

printf("Integer value with positive data: %d\n", a);


printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);

return 0;
}

Output

Integer value with positive data: 9


Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Character Data Type
Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
Example of char
C

// C program to print Integer data types.


#include <stdio.h>

int main()
{
char a = 'a';
char c;

printf("Value of a: %c\n", a);

a++;
printf("Value of a after increment is: %c\n", a);

// c is assigned ASCII values


// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf("Value of c: %c", c);

return 0;
}

Output

Value of a: a
Value of a after increment is: b
Value of c: c
Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used
to store decimal and exponential values. It is used to store decimal numbers (numbers
with floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Example of Float
C

// C Program to demonstrate use


// of Floating types
#include <stdio.h>

int main()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}

Output

9.000000
2.500000
0.000200
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64
bits of decimal numbers or floating points. Since double has more precision as compared
to that float then it is much more obvious that it occupies twice the memory occupied by
the floating-point type. It can easily accommodate about 16 to 17 digits after or before a
decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using the double
keyword:
double var_name;
Example of Double
C
// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}

Output

123123123.000000
12.293123
2312312312.123123
Void Data Type
The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent
nothing. Void is used in multiple ways as function return type, function arguments as void,
and pointers to void.
Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.
int print(void);
// memory allocation function which
// returns a pointer to void.
void *malloc (size_t size);
Example of Void
C

// C program to demonstrate
// use of void pointers
#include <stdio.h>

int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}
Output

30
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof()
operator to check the size of the data types.
Example
C

// C Program to print size of


// different data type in C
#include <stdio.h>

int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n", size_of_int);


printf("The size of char data type : %d\n",
size_of_char);
printf("The size of float data type : %d\n",
size_of_float);
printf("The size of double data type : %d",
size_of_double);

return 0;
}

Output

The size of int data type : 4


The size of char data type : 1
The size of float data type : 4
The size of double data type : 8
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the
memory requirement and format specifiers on the 32-bit GCC compiler.
Size Format
Data Type (bytes) Range Specifier

-32,768 to 32,767
short int 2 %hd
Size Format
Data Type (bytes) Range Specifier

unsigned short
2 0 to 65,535 %hu
int

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 %d
2,147,483,647

-2,147,483,648 to
long int 4 %ld
2,147,483,647

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf


Size Format
Data Type (bytes) Range Specifier

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Note: The long, short, signed and unsigned are datatype modifier that can be used with
some primitive data types to change the size or length of the datatype.
Literals in C

In C, Literals are the constant values that are assigned to the variables. Literals
represent fixed values that cannot be modified. Literals contain memory but
they do not have references as variables. Generally, both terms, constants, and
literals are used interchangeably.
For example, “const int = 5;“, is a constant expression and the value 5 is
referred to as a constant integer literal.
Types of C Literals
There are 4 types of literal in C:
 Integer Literal
 Float Literal
 Character Literal
 String Literal
1. Integer Literals
Integer literals are used to represent and store the integer values only. Integer
literals are expressed in two types i.e.
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to
be read.
For Example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16
in Decimal. Hence the value 16.
There are basically represented into 4 types:
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or
more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Example:
56, 78
b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4,
5, 6, 7).
Example:
045, 076, 06210
c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal
digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Example:
0x23A, 0Xb4C, 0xFEA
d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0,
1).
Example:
0b101, 0B111
B) Suffixes: The Suffixes of the integer literal indicates the type in which it is to
be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.

 int: No suffix is required because integer constant is by default assigned as an int data
type.
 unsigned int: character u or U at the end of an integer constant.
 long int: character l or L at the end of an integer constant.
 unsigned long int: character ul or UL at the end of an integer constant.
 long long int: character ll or LL at the end of an integer constant.
 unsigned long long int: character ull or ULL at the end of an integer constant.
Example:
C

#include <stdio.h>

int main()
{

// constant integer literal


const int intVal = 10;

printf("Integer Literal:%d \n", intVal);


return 0;
}

Output

Integer Literal:10
2. Floating-Point Literals
These are used to represent and store real numbers. The real number has an integer part,
real part, fractional part, and exponential part. The floating-point literals can be stored
either in decimal form or exponential form. While representing the floating-point decimals
one must keep two things in mind to produce valid literal:
 In the decimal form, one must include the integer part, or fractional part, or both,
otherwise, it will lead to an error.
 In the exponential form, one must include both the significand and exponent part,
otherwise, it will lead to an error.
A few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215e-10L
10.5E-3
Invalid Floating Literals:
123E
1250f
0.e879
Example:
C
#include <stdio.h>

int main()
{
// constant float literal
const float floatVal = 4.14;

printf("Floating point literal: %.2f\n",


floatVal);
return 0;
}

Output

Floating point literal: 4.14


3. Character Literals
This refers to the literal that is used to store a single character within a single quote. To
store multiple characters, one needs to use a character array. Storing more than one
character within a single quote will throw a warning and display just the last character of
the literal. It gives rise to the following two representations:
 char type: This is used to store normal character literal or narrow-character literals.
Example:
char chr = 'G';
Example:
C

#include <stdio.h>

int main()
{
// constant char literal
const char charVal = 'A';

printf("Character Literal: %c\n",


charVal);
return 0;
}

Output

Character Literal: A

Escape Sequences: There are various special characters that one can use to perform
various operations.
4. String Literals
String literals are similar to that character literals, except that they can store multiple
characters and uses a double quote to store the same. It can also accommodate the
special characters and escape sequences mentioned in the table above. We can break a
long line into multiple lines using string literal and can separate them with the help of white
spaces.
Example:
char stringVal[] = "GeeksforGeeks";
Example:
C

#include <stdio.h>

int main()
{
const char str[]
= "Welcome\nTo\nGeeks\tFor\tGeeks";
printf("%s", str);
return 0;
}

Output

Welcome
To
Geeks For Geeks

Escape Sequence in C

The escape sequence in C is the characters or the sequence of characters that


can be used inside the string literal. The purpose of the escape sequence is to
represent the characters that cannot be used normally using the keyboard.
Some escape sequence characters are the part of ASCII charset but some are
not.
Different escape sequences represent different characters but the output is
dependent on the compiler you are using.
Escape Sequence List
The table below lists some common escape sequences in C language.
Escape
Sequence Name Description

\a Alarm or Beep It is used to generate a bell sound in the C program.


Escape
Sequence Name Description

\b Backspace It is used to move the cursor one place backward.

It is used to move the cursor to the start of the next


\f Form Feed
logical page.

\n New Line It moves the cursor to the start of the next line.

\r Carriage Return It moves the cursor to the start of the current line.

It inserts some whitespace to the left of the cursor and


\t Horizontal Tab
moves the cursor accordingly.

\v Vertical Tab It is used to insert vertical space.

\\ Backlash Use to insert backslash character.

\’ Single Quote It is used to display a single quotation mark.

\” Double Quote It is used to display double quotation marks.

\? Question Mark It is used to display a question mark.

\ooo Octal Number It is used to represent an octal number.

Hexadecimal
\xhh It represents the hexadecimal number.
Number
Escape
Sequence Name Description

\0 NULL It represents the NULL character.

\e Escape sequence It represents the ASCII escape character.

\s Space Character It represents the ASCII space character.

\d Delete Character It represents the ASCII DEL character.

Out of all these escape sequences, \n and \0 are used the most. In fact, escape
sequences like \f, \a, are not even used by programmers nowadays. To learn
how to handle strings, characters, and escape sequences in larger programs,
the C Programming Course Online with Data Structures offers lessons on
string manipulation and formatting

Escape Sequence in C Examples


The following are the escape sequence examples that demonstrate how to
use different escape sequences in C language.
1. Example to demonstrate how to use \a escape sequence in C
C

// C program to illustrate \a escape sequence


#include <stdio.h>

int main(void)
{
// output may depend upon the compiler
printf("My mobile number "
"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
return (0);
}

Output
My mobile number is 7873923408
2. Example to demonstrate how to use \b escape sequence in C
C

// 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 \b\b\b\b\b\bHi Geeks");
return (0);
}

Output
Hello Hi Geeks
3. Example to demonstrate how to use \n escape sequence in C
C

// 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("GeeksforGeeks");
return (0);
}

Output
Hello
GeeksforGeeks
4. Example to demonstrate how to use \t escape sequence in C
C

// 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.
5. Example to demonstrate how to use \v escape sequence in C
C

// 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\v");

printf("Welcome to GFG");

return (0);
}

Output
Hello friends
Welcome to GFG
6. Example to demonstrate how to use \r escape sequence in C
C

// 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 Geeks \rGeeksfor");
return (0);
}

Output
Hello Geeks
Geeksfor
7. Example to demonstrate how to use \\ escape sequence in C
C

// 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
Hello\GFG
Explanation: It contains two ‘\’ which means we want print ‘\’ as output.
8. Example to demonstrate how to use \’ and \” escape sequence in C
C

// 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
9. Example to demonstrate how to use \? escape sequence in C
C

// 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
??!
10. Example to demonstrate how to use \ooo escape sequence in C
C

// 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\072\065";
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 a maximum of three. Here 072 is the
octal notation, first, it is converted to decimal notation which is the ASCII
value of char ‘:’. At the place of \072, there is: and the output is A:5.
11. Example to demonstrate how to use \xhh escape sequence in C
C

// 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 the char ‘J’. Therefore at the
place of \x4a, we can write J. So the output is BJ.

bool in C


The bool in C is a fundamental data type in most that can hold one of two
values: true or false. It is used to represent logical values and is commonly used
in programming to control the flow of execution in decision-making statements
such as if-else statements, while loops, and for loops. In this article, we will
explore how to use the bool data type in C.
Boolean in C
In C, the bool data type is not a built-in data type. However, the C99 standard
for C language supports bool variables. Boolean can store values as true-false,
0-1, or can be yes-no. It can be implemented in C using different methods as
mentioned below:
1. Using header file “stdbool.h”
2. Using Enumeration type
3. Using define to declare boolean values
If you’re interested in learning how to use bool in conjunction with complex data
structures, the C Programming Course Online with Data
Structures provides practical lessons on data types and logical operations.
1. Using Header File “stdbool.h”
To use bool in C, you must include the header file “stdbool.h”. After including
the stdbool.h library we can use the data type as boolean is not available with
stdio.h library.
Below is the implementation of the boolean in C:
C

// C Program to implement
// Boolean data type
#include <stdbool.h>

// Main Function
int main()
{
// Boolean data types declared
bool a = true;
bool b = false;

printf("True : %d\n", a);


printf("False : %d", b);

return 0;
}

Output

True : 1
False : 0
If we save the above program as a .c file, it will not compile. But if we save it as
a .cpp file, it will work fine.
2. Using the Enumeration Type
Alternatively, you can implement bool in C using an enumeration type. Here
rather than importing the library, we declare an enumeration type so as to use
bool as the data type.
Below is an example of using an enumeration-type approach:
C

#include <stdio.h>

typedef enum { false, true } bool;

int main()
{
bool a = true;
bool b = false;

printf("True : %d\n", a);


printf("False : %d", b);

return 0;
}

Output

True : 1
False : 0
3. Using Define to Declare Boolean Values
In this case, the false value is assigned the integer value of 0, and the true value is
assigned the integer value of 1. You can also use an int or a char with a value of either 0
(false) or 1 (true) to represent the bool data type in C.
Below is the implementation of the above approach:
C

#define bool int


#define false 0
#define true 1

int main()
{
bool a = true;
bool b = false;

printf("True : %d\n", a);


printf("False : %d", b);

return 0;
}

Output

True : 1
False : 0
Using Bool in Conditional Statements
The bool data type is commonly used in conditional statements such as if-else
statements. Condition like if a is greater than equal to b or else b is greater than a can be
implemented using boolean. These conditions using conditional operator like “==” , “>” , <”
, “!=” ,etc return boolean values.
Below is the implementation of conditional statements:
C

// C Program to implement
// conditional statements
#include <stdbool.h>
#include <stdio.h>

// Main Function
int main()
{

// Integers declared
int a = 3;
int b = 4;

// Conditional Statements
if (a > b) {
printf("a is greater\n");
}
else {
printf("a is smaller\n");
}

printf("%d is the result of a>b", a > b);

return 0;
}

Output

a is smaller
0 is the result of a>b
Using bool in Loops
The bool data type is also used in loops such as while loops and for loops. Conditional
statements are one of the most important parts used with loops. We can’t define
breakpoints of loops without using conditional statements which return boolean values,
without conditional statement loop becomes infinite loop.
Below is the implementation of the above approach:
C

// C Program to demonstrate
// Using bool in loops
#include <stdbool.h>
#include <stdio.h>

// Main Function
int main()
{
// boolean declared
bool a = true;
int i = 0;

// while loop
while (a) {
printf("i is %d\n", i);
i++;

// Conditional statement returning


// true or false
// Breaking point for loop
if (i > 5) {
a = false;
}
}

return 0;
}

Output
i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
Using bool as a Function Return Type
You can also use the bool data type as a function return type. Function return type adds
the feature to return the result of all the operations performed inside the function.
Below is the implementation of the above approach:
C

// C Program to demonstrate using of


// bool as a function return type
#include <stdbool.h>
#include <stdio.h>

// function returning boolean value


bool is_even(int num)
{
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}

// Main function
int main()
{
// Integer value declared
int num = 5;

// Function calling
if (is_even(num)) {
printf("%d is even\n", num);
}
else {
printf("%d is odd\n", num);
}

return 0;
}

Output

5 is odd
Conclusion
The bool data type is a fundamental data type in most programming languages that can
hold one of two values: true or false. In C, you can use bool variables by including the
header file “stdbool.h”, using an enumeration type, or using an int or a char with a value of
either 0(false) or 1(true) according to the condition defined.
bool in C – FAQs
What is boolean example in C?
Boolean is a data type in C that holds two values that can be either true or false.
What is the C header for bool?
“stdbool.h” is the C header for bool.
What is the size of boolean in C?
Boolean in C has the size of 1 byte as it needs only two values 0 and 1.
Does C use bool or boolean?
Boolean is a data type that can store values as true or false, and we use it in C as a bool.

You might also like