C programming language
C programming language
uiopasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmqwertyuiopasdfghjklzx
cvbnmqwertyuiopasdfghjklzxcvbnmq
C programming language
wertyuiopasdfghjklzxcvbnmqwertyui
1ere année GBM
23/09/2024
opasdfghjklzxcvbnmqwertyuiopasdfg
geeksforgeeks.org
Université Paris Dauphine_Maude Manouvrier
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmrtyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwert
yuiopasdfghjklzxcvbnmqwertyuiopas
C Language Introduction
Last Updated : 03 Sep, 2024
int main() {
int a = 10;
printf("%d", a);
return 0;
}
Output
10
Let us analyze the structure of our program line by line.
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:
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 type is a collection of data with values having fixed
values, meaning as well as its characteristics.
The data types in C can be classified as follows:
Types Description
Primitive Data Primitive data types are the most basic data types that are used for
Types representing simple values such as integers, float, characters, etc.
User Defined
The user-defined data types are defined by the user himself.
Data Types
The data types that are derived from the primitive or built-in
Derived Types
datatypes are referred to as Derived Data Types.
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
float 4 %f
1.2E-38 to 3.4E+38
double 8 %lf
1.7E-308 to 1.7E+308
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.
Example of int
C
#include <stdio.h>
int main()
int a = 9;
int b = -9;
int c = 89U;
c);
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
Example of char
C
#include <stdio.h>
int main()
char a = 'a';
char c;
// character 'c'
c = 99;
return 0;
Output
Value of a: a
Value of a after increment is: b
Value of c: c
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
Example of Double
C
// C Program to demonstrate
#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
Example of Void
C
// C program to demonstrate
#include <stdio.h>
int main()
printf("%d", *(int*)ptr);
return 0;
Output
30
#include <stdio.h>
int main()
size_of_char);
size_of_float);
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
Operators in C
Last Updated : 15 Jul, 2024
For example,
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands ‘a’
and ‘b’.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types
based on their functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on
operands. There are 9 arithmetic operators in C language:
S. No. Symbol Operator Description Syntax
Adds two
+ Plus numeric a+b
1 values.
Subtracts right
– Minus operand from a–b
2 left operand.
Multiply two
* Multiply numeric a*b
3 values.
Divide two
/ Divide numeric a/b
4 values.
Returns the
remainder
after diving
% Modulus the left a%b
operand with
the right
5 operand.
Used to
specify the
+ Unary Plus +a
positive
6 values.
Increases the
++ Increment value of the a++
8 operand by 1.
Decreases the
— Decrement value of the a–
9 operand by 1.
Example of C Arithmetic Operators
C
// C program to illustrate the arithmatic operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
return 0;
}
Output
a + b = 30
a - b = 20
a * b = 125
a / b = 5
a % b = 0
+a = 25
-a = -25
a++ = 25
a-- = 26
2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All
these operators are binary operators that return true or false values as the result of
comparison.
These are a total of 6 relational operators in C:
S. No. Symbol Operator Description Syntax
Returns true if
the left
operand is less
< Less than a<b
than the right
operand. Else
1 false
Returns true if
the left
operand is
> Greater than greater than a>b
the right
operand. Else
2 false
Returns true if
the left
operand is less
Less than or
<= than or equal a <= b
equal to
to the right
operand. Else
3 false
Returns true if
the left
operand is
Greater than
>= greater than or a >= b
or equal to
equal to right
operand. Else
4 false
Returns true if
both the
== Equal to a == b
operands are
5 equal.
Returns true if
both the
!= Not equal to a != b
operands are
6 NOT equal.
Example of C Relational Operators
C
// C program to illustrate the relational operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
return 0;
}
Output
a < b : 0
a > b : 1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Returns true if
both the
&& Logical AND a && b
operands are
1 true.
Returns true if
both or any of
|| Logical OR a || b
the operand is
2 true.
Returns true if
! Logical NOT the operand is !a
3 false.
Example of Logical Operators in C
C
// C program to illustrate the logical operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
return 0;
}
Output
a && b : 1
a || b : 1
!a: 0
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. Mathematical operations such as addition, subtraction, multiplication, etc.
can be performed at the bit level for faster processing.
There are 6 bitwise operators in C:
S. No. Symbol Operator Description Syntax
Performs bit-
by-bit AND
& Bitwise AND operation and a&b
returns the
1 result.
Performs bit-
by-bit OR
| Bitwise OR operation and a|b
returns the
2 result.
Performs bit-
by-bit XOR
^ Bitwise XOR operation and a^b
returns the
3 result.
number.
Shifts the
number in
binary form
Bitwise by one place
<< a << b
Leftshift in the
operation and
returns the
5 result.
Shifts the
number in
binary form
Bitwise by one place
>> a >> b
Rightshilft in the
operation and
returns the
6 result.
Example of Bitwise Operators
C
// C program to illustrate the bitwise operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
return 0;
}
Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of
the assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to
provide multiple operations using single operator. These operators are called
compound operators.
In C, there are 11 assignment operators :
S. No. Symbol Operator Description Syntax
Assign the
value of the
Simple
= right operand a=b
Assignment
to the left
1 operand.
Subtract the
right operand
and left
Minus and
-= operand and a -= b
assign
assign this
value to the
3 left operand.
Multiply the
right operand
and left
Multiply and
*= operand and a *= b
assign
assign this
value to the
4 left operand.
left operand.
Assign the
remainder in
the division of
Modulus and
%= left operand a %= b
assign
with the right
operand to the
6 left operand.
Performs
bitwise AND
AND and and assigns
&= a &= b
assign this value to
the left
7 operand.
Performs
bitwise OR
OR and and assigns
|= a |= b
assign this value to
the left
8 operand.
Performs
bitwise XOR
XOR and and assigns
^= a ^= b
assign this value to
the left
9 operand.
Performs
bitwise
Rightshift Rightshift and
>>= a >>= b
and assign assign this
value to the
10 left operand.
Performs
bitwise
Leftshift and Leftshift and
<<= a <<= b
assign assign this
value to the
11 left operand.
Example of C Assignment Operators
C
// C program to illustrate the assignment operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a >>= b: 0
a <<= b: 0
6. Other Operators
Apart from the above operators, there are some other operators available in C used
to perform some specific tasks. Some of them are discussed here:
sizeof Operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its
operand.
The result of sizeof is of the unsigned integral type which is usually denoted by
size_t.
Basically, the sizeof the operator is used to compute the size of the variable or
datatype.
Syntax
sizeof (operand)
and
structure_pointer -> member;
To know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.
Cast Operator
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.
A cast is a special operator that forces one data type to be converted into
another.
The most general cast supported by most of the C compilers is as follows −
[ (type) expression ].
Syntax
(new_type) operand;
int main()
{
// integer variable
int num = 10;
int* add_of_num = #
return 0;
}
Output
sizeof(num) = 4 bytes
&num = 0x7ffe2b7bdf8c
*add_of_num = 10
(10 < 5) ? 10 : 20 = 20
(float)num = 10.000000
The below table describes the precedence order and associativity of operators in C.
The precedence of the operator decreases from top to bottom.
Precedence Operator Description Associativity
Postfix increment/decrement
a++ , a– left-to-right
(a is a variable)
Prefix increment/decrement (a
++a , –a right-to-left
is a variable)
Logical negation/bitwise
!,~ right-to-left
complement
* Dereference right-to-left
10 | Bitwise OR left-to-right
12 || Logical OR left-to-right
= Assignment right-to-left
Addition/subtraction
+= , -= right-to-left
assignment
Multiplication/division
*= , /= right-to-left
assignment
Modulus/bitwise AND
%= , &= right-to-left
assignment
Bitwise exclusive/inclusive
^= , |= right-to-left
OR assignment
Q3. What is the difference between the ‘=’ and ‘==’ operators?
Answer:
‘=’ is a type of assignment operator that places the value in right to the variable on
left, Whereas ‘==’ is a type of relational operator that is used to compare two
elements if the elements are equal or not.
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and
output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified
and store it in the given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of
data is in a variable and & is the address operator in C, which tells the compiler to
change the real value of variableOfXType, stored at this address in the memory.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the
console screen.
Syntax:
printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of
data is in a variable and variableOfXType is the variable to be printed.
How to take input and output of basic types in C?
The basic type in C includes types like int, float, char, etc. Inorder to input or output
the specific type, the X in the above syntax is changed with the specific format
specifier of that type. The Syntax for input and output for these are:
Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
Please refer Format specifiers in C for more examples.
C
// C program to show input and output
#include <stdio.h>
int main()
{
return 0;
}
Output
Enter the integer: 10
Entered integer is: 10
#include <stdio.h>
int main()
{
return 0;
}
Output
Enter the Word: GeeksForGeeks
Entered Word is: GeeksForGeeks
Enter the Sentence: Geeks For Geeks
Entered Sentence is: Geeks For Geeks
scanf in C
Last Updated : 06 May, 2023
To know more about format specifiers, refer to this article – Format Specifiers in C
Example:
int var;
scanf(“%d”, &var);
The scanf will write the value input by the user into the integer variable var.
// C program to implement
// scanf
#include <stdio.h>
// Driver code
int main()
int a, b;
scanf("%d", &a);
scanf("%d", &b);
printf("A : %d \t B : %d" ,
a , b);
return 0;
Output
Enter first number: 5
Enter second number: 6
A : 5 B : 6
printf in C
Last Updated : 27 Oct, 2023
C
#include <stdio.h>
int main()
printf("Hello Geek!");
return 0;
Output
Hello Geek!
Formatting in C printf
In C, a value can be a character type, integer type, float type, and so on. To display
and format these values using printf, we have format specifiers that are used in the
formatted string. These format specifiers start with the percentage symbol ‘%’.
%[flags][width][.precision][length]specifier
1. Specifier
It is the character that denotes the type of data. Some commonly used specifiers are:
%d: for printing integers
%f: for printing floating-point numbers
%c: for printing characters
%s: for printing strings
%p: for printing memory addresses
%x: for printing hexadecimal values
Example
printf("%c", char_variable);
2. Width
It is the sub-specifier that denotes the minimum number of characters that will be
printed.
If the number of characters is less than the specified width, the white space will be
used to fill the remaining characters’ places. But if the number of characters is
greater than the specified width, all the characters will be still printed without cutting
off any.
Example
printf("%25s", some_string);
or
printf("%*s", 25, some_string);
3. Precision
Precision subspecifier meaning differs for different format specifiers it is being used
with.
For Integral data(d, i, u, o, x, X): Specifies the minimum number of digits to be
printed. But unlike the width sub-specifier, instead of white spaces, this sub-
specifier adds leading zeroes to the number. If the number has more digits than
the precision, the number is printed as it is.
For Float or Double Data(f, e, a, A): Specifies the number of digits to be
printed after the decimal point.
For String (s): Specifies the length of the string to be printed.
Example
printf("%.10d", some_integer);
printf("%.3f", some_float);
printf("%.25s", some_string);
or
printf("%.*d", 10, some_integer);
printf("%.*f", 3, some_float);
printf("%.*s", 25, some_string);
4. Length
Specifies the length of the data type in the memory. It is used in correspondence
with data type modifiers.
There are 3 length sub-specifiers:
h: With short int and unsigned short int
l: With long int and unsigned long int.
L: With long double
Example
printf("%lf", double_variable);
Examples of printf() in C
Example 1: Print a Variable using Specifier in printf()
In this example, we are printing an integer using a format specifier “%d” which is
used for an integer. In the printf() function we are printing integers along with string
using %d and in the arguments, we have passed variable names in a sequence
corresponding to their format specifiers.
C
#include <stdio.h>
int main()
int num2 = 1;
num1 + num2);
return 0;
Output
The sum of 99 and 1 is 100
In this example, we will specify the width of the output which will be printed by the
printf() function.
C
#include <stdio.h>
int main()
// number to be printed
chars_printed);
chars_printed);
return 0;
Output
Printing num with width 10: 123456
Number of characters printed: 10
Printing num with width 3: 123456
Number of characters printed: 6
As we can see, even if we define the width that is less than the present characters,
all the characters are still printed. Also, we have seen the two ways in which we can
define the width.
Example 3: printf with Precision Sub-Specifier
In this example, we will demonstrate the precision sub-specifier in the printf()
function
C
// sub-specifier
#include <stdio.h>
int main()
// for strings
return 0;
Output
For integers: 0000002451
For floats: 12.45
For strings: Geeks
Example 4: printf with Length Sub-Specifier
C
#include <stdio.h>
int main()
return 0;
Output
Using %d: -1294967296
Using %ld: 3000000000
Related Articles:
sprintf() in C
scanf() in C
The conditional statements (also known as decision control structures) such as if,
if else, switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or
more conditions and make the decision whether to execute a set of statements or
not. These decision-making statements in programming languages decide the
direction of the flow of program execution.
Need of Conditional Statements
There come situations in real life when we need to make some decisions and based
on these decisions, we decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these
decisions we will execute the next block of code. For example, in C if x occurs then
execute y else execute z. There can also be multiple conditions like in C if x occurs
then execute p, else if condition y occurs execute q, else execute r. This condition of
C else-if is one of the many ways of importing multiple conditions.
Types of Conditional Statements in C
break
continue
goto
return
Let’s discuss each of them one by one.
1. if in C
The if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’
after if(condition) then by default if statement will consider the first immediately
below statement to be inside its block.
Flowchart of if Statement
Flow Diagram of if Statement
Example of if in C
C
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
Output
I am Not in if
As the condition present in the if statement is false. So, the block below the if
statement is not executed.
2. if-else in C
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something
else when the condition is false? Here comes the C else statement. We can use
the else statement with the if statement to execute a block of code when the
condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart of if-else Statement
Example of if-else
C
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) {
Output
i is greater than 15
The block of code following the else statement is executed as the condition present
in the if statement is false.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, C allow us to
nested if statements within if statements, i.e, we can place an if statement inside
another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}
The below flowchart helps in visualize the above syntax.
Flowchart of Nested if-else
Example of Nested if-else
C
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
if (i == 20) {
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}
Output
i is smaller than 15
i is smaller than 12 too
4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed. if-else-if ladder is similar to the switch
statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder
Flow Diagram of if-else-if
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Output
i is 20
5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the
switch statement. The switch block consists of cases to be executed based on the
value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot
evaluate any other data type.
Flowchart of switch
Flowchart of switch in C
int main()
{
// variable to be used in switch statement
int var = 2;
return 0;
}
Output
Case 2 is executed
6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar
to the if-else statement. It is also known as the ternary operator as it works on three
operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [false_statements];
Flowchart of Conditional Operator
// driver code
int main()
{
int var;
int flag = 0;
return 0;
}
Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25
7. Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the
functions in a program. They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as
the break statement is encountered from within a loop, the loop iterations stop there,
and control returns from the loop immediately to the first statement after the loop.
Syntax of break
break;
Basically, break statements are used in situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on
some condition.
Example of break
C
// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;
// key to be searched
int key = 3;
return 0;
}
Output
Element found at position: 3
B) continue
This loop control statement is just like the break statement.
The continue statement is opposite to that of the break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute
the next iteration. When the continue statement is executed in the loop, the code
inside the loop following the continue statement will be skipped and the next
iteration of the loop will begin.
Syntax of continue
continue;
Flowchart of Continue
Example of continue
C
// C program to explain the use
// of continue statement
#include <stdio.h>
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
// otherwise print the value of i
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C, it will be local to that if/else block only. You can
use global variables inside the if/else block. If the name of the variable you created in
if/else is as same as any global variable then priority will be given to the `local
variable`.
C
#include <stdio.h>
int main()
{
Output
Before if-else block 0
if block 100
After if block 0
C) goto
The goto statement in C also referred to as the unconditional jump statement can be
used to jump from one point to another within a function.
Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement
marked as a label. Here, a label is a user-defined identifier that indicates the target
statement. The statement immediately followed after ‘label:’ is the destination
statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the
above syntax.
Examples of goto
C
// C program to print numbers
// from 1 to 10 using goto
// statement
#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;
}
Output
1 2 3 4 5 6 7 8 9 10
D) return
The return in C returns the flow of the execution to the function from where it is
called. This statement does not mandatorily need any conditional statements. As
soon as the statement is executed, the flow of the program stops immediately and
returns the control from where it was called. The return statement may or may not
return anything for a void function, but for a non-void function, a return value must
be returned.
Flowchart of return
Flow Diagram of return
Syntax of return
return [expression];
Example of return
C
// C code to illustrate return
// statement
#include <stdio.h>
// returns void
// function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}
Output
The sum is 20
C Functions
Last Updated : 29 Jul, 2024
A function in C is a set of statements that when called perform some specific task.
It is the basic building block of a C program that provides modularity and code
reusability. The programming statements of a function are enclosed within { }
braces, having certain meanings and performing certain operations. They are also
called subroutines or procedures in other languages.
In this article, we will learn about functions, function definition. declaration,
arguments and parameters, return values, and many more.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that
there is a function with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare
the function without using the name of the data variables.
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Declaration
Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly. The below example serves as both a function definition and a declaration.
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
Function Definition in C
Function Call
A function call is a statement that instructs the compiler to execute the function. We
use the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the
sum function. After the function call sum of a and b is returned and control is also
returned back to the main function of the program.
Working of function in C
Note: Function call is neccessary to bring the program control to the function
definition. If not called, the function statements will not be executed.
Example of C Function
C
// C program to show function
// call and definition
#include <stdio.h>
// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
Output
Sum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and
called the function.
Function Return Type
Function return type tells what type of value is returned after all function is executed.
When we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the
function.
Note: Only one value can be returned from a C function. To return multiple values,
we have to use pointers or structures.
Function Arguments
Function Arguments (also known as Function Parameters) are the data that is passed
to a function.
Example:
int function_name(int var1, int var2);
Conditions of Return Types and Arguments
In C programming language, functions can be called either with or without arguments
and might return values. They may or might not return values to the calling
functions.
1. Function with no arguments and no return value
2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value
To know more about function Arguments and Return values refer to the article
– Function Arguments & Return Values in C.
How Does C Function Work?
Working of the C function can be broken into the following steps as mentioned below:
1. Declaring a function: Declaring a function is a step where we declare a function.
Here we define the return types and parameters of the function.
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the function by
passing the arguments in the function.
4. Executing the function: Executing the function is a step where we can run all
the statements inside the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value after
the execution of the function is returned. Exiting the function is the final step
where all the allocated memory to the variables, functions, etc is destroyed before
giving full control to the main function.
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
Types of Functions in C
1. Library Function
A library function is also referred to as a “built-in function”. A compiler package
already exists that contains these functions, each of which has a specific meaning
and is included in the package. Built-in functions have the advantage of being
directly usable without being defined, whereas user-defined functions must be
declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.
Example:
C
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double Number;
Number = 49;
Output
The Square root of 49.00 = 7.00
2. User Defined Function
Functions that the programmer creates are known as User-Defined functions
or “tailor-made functions”. User-defined functions can be improved and modified
according to the need of the programmer. Whenever we write a function that is case-
specific and is not defined in any header file, we need to declare and define our own
functions according to the syntax.
Advantages of User-Defined Functions
Changeable functions can be modified as per need.
The Code of these functions is reusable in other programs.
These functions are easy to understand, debug and maintain.
Example:
C
// C program to show
// user-defined functions
#include <stdio.h>
// Driver code
int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b);
Output
Sum is: 70
Passing Parameters to Functions
The data passed when the function is being invoked is known as the Actual
parameters. In the below program, 10 and 30 are known as actual parameters.
Formal Parameters are the variable and the data type as mentioned in the function
declaration. In the below program, a and b are known as formal parameters.
Passing Parameters to Functions
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the
same locations, so any changes made inside the function are reflected in the caller’s
actual parameters.
Example:
C
// C program to show use of
// call by Reference
#include <stdio.h>
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned
below:
1. The function can reduce the repetition of the same statements in the program.
2. The function makes code readable by providing modularity to our program.
3. There is no fixed number of calling functions it can be called as many times as you
want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking about the
internal working of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation and transfer of program
control.
Conclusion
In this article, we discussed the following points about the function as mentioned
below:
1. The function is the block of code that can be reused as many times as we want
inside a program.
2. To use a function we need to call a function.
3. Function declaration includes function_name, return type, and parameters.
4. Function definition includes the body of the function.
5. The function is of two types user-defined function and library function.
6. In function, we can according to two types call by value and call by reference
according to the values passed.
FAQs on Functions in C
Q1. Define functions.
Answer:
Functions are the block of code that is executed every time they are called during an
execution of a program.
C Arrays
Last Updated : 29 Aug, 2024
C Array Declaration
In C, we have to declare the array like any other variable before using it. We can
declare an array by specifying its name, the type of its elements, and the size of its
dimensions. When we declare an array in C, the compiler allocates the memory block
of the specified size to the array name.
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.
The C arrays are static in nature, i.e., they are allocated memory at the compile time.
Example of Array Declaration
C
// C Program to illustrate the array declaration
#include <stdio.h>
int main()
{
return 0;
}
Output
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the
array is declared or allocated memory, the elements of the array contain some
garbage value. So, we need to initialize the array to some meaningful value. There
are multiple ways in which we can initialize an array in C.
1. Array Initialization with Declaration
In this method, we initialize the array along with its declaration. We use an initializer
list to initialize multiple elements of the array. An initializer list is the list of values
enclosed within braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};
2. Array Initialization with Declaration without Size
If we initialize an array using an initializer list, we can skip declaring the size of the
array as the compiler can automatically deduce the size of the array in these cases.
The size of the array in these cases is equal to the number of elements present in the
initializer list as the compiler can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the compiler.
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to assign the
value to each element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization in C
C
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
Output
Access Array Elements
We can access any element of an array in C using the array subscript
operator [ ] and the index value i of the element.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first
element is at index 0 and the last element is at N – 1 where N is the number of
elements in the array.
int main()
{
return 0;
}
Output
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15
Update Array Element
We can update the value of an element at the given index i in a similar way to
accessing an element by using the array subscript operator [ ] and assignment
operator =.
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C
array traversal, we use loops to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++) {
array_name[i];
}
How to use Array in C?
The following program demonstrates how to use an array in the C programming
language:
C
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
Output
Elements in Array: 10 20 100 40 50
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as
follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array in C
The One-dimensional arrays, also known as 1-D arrays in C are those arrays that
have only one dimension.
Syntax of 1D Array in C
array_name [size];
Example of 1D Array in C
C
// C Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
// 1d array declaration
int arr[5];
// 1d array initialization using for loop
for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}
return 0;
}
Output
Elements of Array: 1 0 1 4 9
Array of Characters (Strings)
In C, we store the words, i.e., a sequence of characters in the form of an array of
characters terminated by a NULL character. These are called strings in C language.
C
// C Program to illustrate strings
#include <stdio.h>
int main()
{
// printing string
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
}
return 0;
}
Output
Geeks
To know more about strings, refer to this article – Strings in C
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension.
Some of the popular multidimensional arrays are 2D arrays and 3D arrays. We can
declare arrays with more dimensions than 3d arrays but they are avoided as they get
very complex and occupy a large amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions. They can be visualized in the form of rows and columns organized in a
two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
size1: Size of the first dimension.
size2: Size of the second dimension.
Example of 2D Array in C
C
// C Program to illustrate 2d array
#include <stdio.h>
int main()
{
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
Output
2D Array:
10 20 30
40 50 60
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D
Array. A 3D array has exactly three dimensions. It can be visualized as a collection of
2D arrays stacked on top of each other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];
Example of 3D Array
C
// C Program to illustrate the 3d array
#include <stdio.h>
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n \n");
}
return 0;
}
Output
10 20
30 40
50 60
0 0
int main()
{
Output
Address Stored in Array name: 0x7ffcab67d8e0
Address of 1st Array Element: 0x7ffcab67d8e0
Array elements using pointer: 10 20 30 40 50
To know more about the relationship between an array and a pointer, refer to this
article – Pointer to an Arrays | Array Pointer
Passing an Array to a Function in C
An array is always passed as pointers to a function in C. Whenever we try to pass an
array to a function, it decays to the pointer and then passed as a pointer to the first
element of an array.
We can verify this using the following C Program:
C
// C Program to pass an array to a function
#include <stdio.h>
// driver code
int main()
{
Output
Size of Array in main(): 20
Size of Array in Functions: 8
Array Elements: 10 20 30 40 50
Return an Array from a Function in C
In C, we can only return a single value from a function. To return multiple values or
elements, we have to use pointers. We can return an array from a function using a
pointer to the first element of that array.
C
// C Program to return array from a function
#include <stdio.h>
// function
int* func()
{
static int arr[5] = { 1, 2, 3, 4, 5 };
return arr;
}
// driver code
int main()
{
Output
Array Elements: 1 2 3 4 5
Note: You may have noticed that we declared static array using static keyword. This
is due to the fact that when a function returns a value, all the local variables and
other entities declared inside that function are deleted. So, if we create a local array
instead of static, we will get segmentation fault while trying to access the array in the
main function.
Properties of Arrays in C
It is very important to understand the properties of the C array so that we can avoid
bugs while using it. The following are the main properties of an array in C:
1. Fixed Size
The array in C is a fixed-size collection of elements. The size of the array must be
known at the compile time and it cannot be changed once it is declared.
2. Homogeneous Collection
We can only store one type of element in an array. There is no restriction on the
number of elements but the type of all of these elements must be the same.
3. Indexing in Array
The array index always starts with 0 in C language. It means that the index of the
first element of the array will be 0 and the last element will be N – 1.
4. Dimensions of an Array
A dimension of an array is the number of indexes required to refer to an element in
the array. It is the number of directions in which you can grow the array size.
5. Contiguous Storage
All the elements in the array are stored continuously one after another in the
memory. It is one of the defining properties of the array in C which is also the reason
why random access is possible in the array.
6. Random Access
The array in C provides random access to its element i.e we can get to a random
element at any index of the array in constant time complexity just by using its index
number.
7. No Index Out of Bounds Checking
There is no index out-of-bounds checking in C/C++, for example, the following
program compiles fine but may produce unexpected output when run.
C
// This C program compiles fine
// as index out of bound
// is not checked in C.
#include <stdio.h>
int main()
{
int arr[2];
return 0;
}
Output
0 0
In C, it is not a compiler error to initialize an array with more elements than the
specified size. For example, the below program compiles fine and shows just a
Warning.
C
#include <stdio.h>
int main()
{
return 0;
}
Output
Warnings:
prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:33: note: (near initialization for 'arr')
Examples of Array in C
Example 1: C Program to perform array input and output.
In this program, we will use scanf() and print() function to take input and print output
for the array.
C
// C Program to perform input and output on array
#include <stdio.h>
int main()
{
Output
Array Elements: 15775231 0 0 0 4195776
Input
5 7 9 1 4
Output
Array Elements: 5 7 9 1 4
Example 2: C Program to print the average of the given list of numbers
In this program, we will store the numbers in an array and traverse it to calculate the
average of the number stored.
C
// C Program to the average to two numbers
#include <stdio.h>
int sum = 0;
// calculating cumulative sum of all the array elements
for (int i = 0; i < size; i++) {
sum += arr[i];
}
// returning average
return sum / size;
}
// driver code
int main()
{
Output
Array Elements: 10 20 30 40 50
Average: 30.00
Example 3: C Program to find the largest number in the array.
C
// C Program to find the largest number in the array.
#include <stdio.h>
// Driver code
int main()
{
int arr[10]
= { 135, 165, 1, 16, 511, 65, 654, 654, 169, 4 };
return 0;
}
Output
Largest Number in the Array: 654
Advantages of Array in C
The following are the main advantages of an array:
1. Random and fast access of elements using the array index.
2. Use of fewer lines of code as it creates a single array of multiple elements.
3. Traversal through the array becomes easy using a single loop.
4. Sorting becomes easy as it can be accomplished by writing fewer lines of code.
Disadvantages of Array in C
1. Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to
be rearranged after insertion and deletion.
Conclusion
The array is one of the most used and important data structures in C. It is one of the
core concepts of C language that is used in every other program. Though it is
important to know about its limitation so that we can take advantage of its
functionality.
C Arrays – FAQs
Define Array in C.
An array is a fixed-size homogeneous collection of elements that are stored in a
contiguous memory location.
Let us now look at a sample program to get a clear understanding of declaring, and
initializing a string in C, and also how to print a string with its size.
C String Example
C
#include <stdio.h>
#include <string.h>
int main()
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
return 0;
Output
Geeks
Length of string str is 5
We can see in the above program that strings can be printed using normal printf
statements just like we print any other variable. Unlike arrays, we do not need to
print a string, character by character.
Note: The C language does not provide an inbuilt data type for strings but it has an
access specifier “%s” which can be used to print and read strings directly.
#include<stdio.h>
int main()
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
Input
GeeksforGeeks
Output
GeeksforGeeks
You can see in the above program that the string can also be read using a single
scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign
with the string name ‘str’ in scanf statement! To understand this you will have to
recall your knowledge of scanf.
We know that the ‘&’ sign is used to provide the address of the variable to the scanf()
function to store the value read in memory. As str[] is a character array so using str
without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have
not used ‘&’ in this case as we are already providing the base address of the string to
scanf.
Now consider one more example,
C
// whitespaces
#include <stdio.h>
// driver code
int main()
char str[20];
scanf("%s", str);
printf("%s", str);
return 0;
Input
Geeks for Geeks
Output
Geeks
Here, the string is read only till the whitespace is encountered.
Note: After declaration, if we want to assign some other text to the string, we have
to assign it one by one or use the built-in strcpy() function because the direct
assignment of the string literal to character array is only possible in declaration.
How to Read a String Separated by Whitespaces in C?
We can use multiple methods to read a string separated by spaces in C. The two of
the common ones are:
1. We can use the fgets() function to read a line of string and gets() to read
characters from the standard input (stdin) and store them as a C string until a
newline character or the End-of-file (EOF) is reached.
2. We can also scanset characters inside the scanf() function
1. Example of String Input using gets()
C
// C program to illustrate
// fgets()
#include <stdio.h>
#define MAX 50
int main()
char str[MAX];
puts(str);
return 0;
Input
GeeksforGeeks
Output
String is:
GeeksforGeeks
2. Example of String Input using scanset
C
// scanset characters
#include <stdio.h>
// driver code
int main()
char str[20];
scanf("%[^\n]s", str);
printf("%s", str);
return 0;
Input
Geeks for Geeks
Output
Geeks for Geeks
C String Length
The length of the string is the number of characters present in the string except for
the NULL character. We can easily find the length of the string using the loop to
count the characters from the start till the NULL character is found.
Passing Strings to Function
As strings are character arrays, we can pass strings to functions in the same way
we pass an array to a function. Below is a sample program to do this:
C
#include <stdio.h>
int main()
// to a different function
printStr(str);
return 0;
Output:
String is : GeeksforGeeks
Note: We can’t read a string value with spaces, we can use either gets() or fgets() in
the C programming language.
Strings and Pointers in C
In Arrays, the variable name points to the address of the first element.
Below is the memory representation of the string str = “Geeks”.
Similar to arrays, In C, we can create a character pointer to a string that points to the
starting address of the string which is the first character of the string. The string can
be accessed with the help of pointers as shown in the below example.
C
// C program to print string using Pointers
#include <stdio.h>
int main()
printf("%c", *ptr);
ptr++;
return 0;
}
Output
GeeksforGeeks
Standard C Library – String.h Functions
The C language comes bundled with <string.h> which contains some useful string-
handling functions. Some of them are as follows:
Function Name Description
strlen(string_name
Returns the length of string name.
)
Compares the first string with the second string. If strings are the
strcmp(str1, str2)
same it returns 0.
Concat s1 string with s2 string and the result is stored in the first
strcat(s1, s2)
string.
C Pointers
Last Updated : 24 Jul, 2024
Pointers are one of the core components of the C programming language. A pointer can be
used to store the memory address of other variables, functions, or even other pointers. The
use of pointers allows low-level memory access, dynamic memory allocation, and many other
functionality in C.
In this article, we will discuss C pointers in detail, their types, uses, advantages, and
disadvantages with examples.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.
As the pointers in C store the memory addresses, their size is independent of the type of data
they are pointing to. This size of pointers in C only depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype * ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to
functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer,
we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not initialized.
Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable.
We generally use the ( &: ampersand ) addressof operator to get the memory address of a
variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is called pointer
definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value before
starting using it. Otherwise, it may lead to number of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address
specified in the pointer. We use the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereferencing a Pointer in C
C Pointer Example
C
// C program to illustrate Pointers
#include <stdio.h>
void geeks()
{
int var = 10;
// Driver program
int main()
{
geeks();
return 0;
}
Output
Value at ptr = 0x7ffca84068dc
Value at var = 10
Value at *ptr = 10
Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter on which we
are defining their types. If we consider the type of variable stored in the memory location
pointed by the pointer, then the pointers can be classified into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
Pointer to Arrays exhibits some interesting properties which we discussed later in this article.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It
can be declared in the same way as we declare the other primitive data types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the
sense that instead of pointing to the data, they point to the code. Let’s consider a function
prototype – int func (int, char), the function pointer for this function will be
Syntax
int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer.
Such pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data
value, they point to another pointer.
Syntax
datatype ** pointer_name;
Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3,
****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be
created by assigning a NULL value to the pointer. A pointer of any type can be assigned the
NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any type and
can be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of
C-pointers can cause problems in our programs and can eventually cause them to crash. If
values is updated using wild pointers, they could cause data abort or data corruption.
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be
modified once it is defined. It will always point to the same memory address.
Syntax
data_type * const pointer_name;
// dummy structure
struct str {
};
// dummy function
void func(int a, int b){};
int main()
{
// dummy variables definitions
int a = 10;
char c = 'G';
struct str x;
// printing sizes
printf("Size of Integer Pointer \t:\t%d bytes\n",
sizeof(ptr_int));
printf("Size of Character Pointer\t:\t%d bytes\n",
sizeof(ptr_char));
printf("Size of Structure Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
printf("Size of Function Pointer\t:\t%d bytes\n",
sizeof(ptr_func));
printf("Size of NULL Void Pointer\t:\t%d bytes",
sizeof(ptr_vn));
return 0;
}
Output
Size of Integer Pointer : 8 bytes
Size of Character Pointer : 8 bytes
Size of Structure Pointer : 8 bytes
Size of Function Pointer : 8 bytes
Size of NULL Void Pointer : 8 bytes
As we can see, no matter what the type of pointer it is, the size of each and every pointer is the
same.
Now, one may wonder that if the size of all the pointers is the same, then why do we need to
declare the pointer type in the declaration? The type declaration is needed in the pointer for
dereferencing and pointer arithmetic purposes.
C Pointer Arithmetic
The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed
on a pointer. It is slightly different from the ones that we generally use for mathematical
calculations as only a limited set of operations can be performed on pointers. These operations
include:
Increment in a Pointer
Decrement in a Pointer
Addition of integer to a pointer
Subtraction of integer to a pointer
Subtracting two pointers of the same type
Comparison of pointers of the same type.
Assignment of pointers of the same type.
C
// C program to illustrate Pointer Arithmetic
#include <stdio.h>
int main()
{
// Declare an array
int v[3] = { 10, 100, 200 };
Output
Value of *ptr = 10
Value of ptr = 0x7ffcfe7a77a0
C
// C Program to access array elements using pointer
#include <stdio.h>
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15 };
return;
}
// Driver program
int main()
{
geeks();
return 0;
}
C Preprocessors
Last Updated : 28 Aug, 2024
Preprocessors are programs that process the source code before compilation. Several
steps are involved between writing a program and executing a program in C. Let us
have a look at these steps before we actually start learning about Preprocessors.
You can see the intermediate steps in the above diagram. The source code written by
programmers is first stored in a file, let the name be “program.c“. This file is then
processed by preprocessors and an expanded source code file is generated named
“program.i”. This expanded file is compiled by the compiler and an object code file is
generated named “program.obj”. Finally, the linker links this object code file to the
object code of the library functions to generate the executable file “program.exe”.
Preprocessor Directives in C
Preprocessor programs provide preprocessor directives that tell the compiler to
preprocess the source code before compiling. All of these preprocessor directives
begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that whatever statement
starts with a ‘#’ will go to the preprocessor program to get executed. We can place
these preprocessor directives anywhere in our program.
Examples of some preprocessor directives are: #include, #define, #ifndef, etc.
Note Remember that the # symbol only provides a path to the preprocessor, and a
command such as include is processed by the preprocessor program. For example,
#include will include the code or content of the specified file in your program.
// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Output
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with
5. The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is
macro expansion.
Note There is no semi-colon (;) at the end of the macro definition. Macro definitions
do not need a semi-colon to end.
There are also some Predefined Macros in C which are useful in providing various
functionalities to our program.
Macros With Arguments
We can also pass arguments to macros. Macros defined with arguments work
similarly to functions.
Example
#define foo(a, b) a + b
#define func(r) r * r
Let us understand this with a program:
C
// C Program to illustrate function like macros
#include <stdio.h>
int main()
{
int l1 = 10, l2 = 5, area;
return 0;
}
Output
Area of rectangle is: 50
We can see from the above program that whenever the compiler finds AREA(l, b) in
the program, it replaces it with the statement (l*b). Not only this, but the values
passed to the macro template AREA(l, b) will also be replaced in the statement (l*b).
Therefore AREA(10, 5) will be equal to 10*5.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source
code program. The #include preprocessor directive is used to include the header
files in the C program.
There are two types of files that can be included by the user in the
program:
Standard Header Files
The standard header files contain definitions of pre-defined functions like printf(),
scanf(), etc. These files must be included to work with these functions. Different
functions are declared in different header files.
For example, standard I/O functions are in the ‘iostream’ file whereas functions that
perform string operations are in the ‘string’ file.
Syntax
#include <file_name>
where file_name is the name of the header file to be included. The ‘<‘ and ‘>’
brackets tell the compiler to look for the file in the standard directory.
User-defined Header Files
When a program becomes very large, it is a good practice to divide it into smaller
files and include them whenever needed. These types of files are user-defined
header files.
Syntax
#include "filename"
The double quotes ( ” ” ) tell the compiler to search for the header file in
the source file’s directory.
3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a
specific portion of the program or to skip the compilation of some specific part of the
program based on some conditions. There are the following preprocessor directives
that are used to insert conditional code:
1. #if Directive
2. #ifdef Directive
3. #ifndef Directive
4. #else Directive
5. #elif Directive
6. #endif Directive
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives
which means the preprocessing of these directives is completed.
Syntax
#ifdef macro_name
// Code to be executed if macro_name is defined
#ifndef macro_name
// Code to be executed if macro_name is not defined
#if constant_expr
// Code to be executed if constant_expression is true
#elif another_constant_expr
// Code to be excuted if another_constant_expression is true
#else
// Code to be excuted if none of the above conditions are true
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements
will execute normally, but if it is not defined, the compiler will simply skip this block
of statements.
Example
The below example demonstrates the use of #include #if, #elif, #else, and #endif
preprocessor directives.
C
//program to demonstrates the use of #if, #elif, #else,
// and #endif preprocessor directives.
#include <stdio.h>
// defining PI
#define PI 3.14159
int main()
{
#ifdef PI
printf("PI is defined\n");
#elif defined(SQUARE)
printf("Square is defined\n");
#else
#error "Neither PI nor SQUARE is defined"
#endif
#ifndef SQUARE
printf("Square is not defined");
#else
cout << "Square is defined" << endl;
#endif
return 0;
}
Output
PI is defined
Square is not defined
4. Other Directives
Apart from the above directives, there are two more directives that are not
commonly used. These are:
1. #undef Directive
2. #pragma Directive
1. #undef Directive
The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement,
every “#ifdef LIMIT” statement will evaluate as false.
Example
The below example demonstrates the working of #undef Directive.
C
#include <stdio.h>
// defining MIN_VALUE
#define MIN_VALUE 10
int main() {
// Undefining and redefining MIN_VALUE
printf("Min value is: %d\n",MIN_VALUE);
//undefining max value
#undef MIN_VALUE
printf("Min value after undef and again redefining it: %d\n", MIN_VALUE);
return 0;
}
Output
Min value is: 10
Min value after undef and again redefining it: 20
2. #pragma Directive
This directive is a special purpose directive and is used to turn on or off some
features. These types of directives are compiler-specific, i.e., they vary from compiler
to compiler.
Syntax
#pragma directive
Some of the #pragma directives are discussed below:
1. #pragma startup: These directives help us to specify the functions that are
needed to run before program startup (before the control passes to main()).
2. #pragma exit: These directives help us to specify the functions that are needed
to run just before the program exit (just before the control returns from main()).
Below program will not work with GCC compilers.
Example
The below program illustrate the use of #pragma exit and pragma startup
C
// C program to illustrate the #pragma exit and pragma
// startup
#include <stdio.h>
void func1();
void func2();
// driver code
int main()
{
void func1();
void func2();
printf("Inside main()\n");
return 0;
}
Expected Output
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:
Inside main()c
This happens because GCC does not support #pragma startup or exit. However, you
can use the below code for the expected output on GCC compilers.
C
#include <stdio.h>
void func1();
void func2();
void func1()
{
printf("Inside func1()\n");
}
void func2()
{
printf("Inside func2()\n");
}
int main()
{
printf("Inside main()\n");
return 0;
}
Output
Inside func1()
Inside main()
Inside func2()
In the above program, we have used some specific syntaxes so that one of the
functions executes before the main function and the other executes after the main
function.
#pragma warn Directive
This directive is used to hide the warning message which is displayed during
compilation. We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warnings which are raised when a
function that is supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warnings which are raised when a
function does not use the parameters passed to it.
#pragma warn -rch: This directive hides those warnings which are raised when a
code is unreachable. For example, any code written after the return statement in a
function is unreachable.
Frequently Asked Questions on C Preprocessors
How Does a Macro with Arguments Differ from a Function in C?
Macros with arguments are expanded at compile time, unlike functions, which are
executed at runtime. This means that the macro performs text substitution before
the program is compiled, so it doesn’t have the overhead of a function call that
results in a faster execution but lack type checking.