C Pointers

In this tutorial, you’ll learn about pointers; what pointers are, how do you use them and the common mistakes you might face when working with them with the help of examples.

Pointers are powerful features of C and C++ programming. Before we learn pointers, let’s learn about addresses in C programming.


Address in C

If you have a variable var in your program, &var will give you its address in the memory.

We have used address numerous times while using the scanf() function.

scanf("%d", &var);

Here, the value entered by the user is stored in the address of var variable. Let’s take a working example.

#include <stdio.h>
int main()
{
  int var = 5;
  printf("var: %d\n", var);

  // Notice the use of & before var
  printf("address of var: %p", &var);  
  return 0;
}

Output

var: 5 
address of var: 2686778

Note: You will probably get a different address when you run the above code.


C Pointers

Pointers (pointer variables) are special variables that are used to store addresses rather than values.

Pointer Syntax

Here is how we can declare pointers.

int* p;

Here, we have declared a pointer p of int type.

You can also declare pointers in these ways.

int *p1;
int * p2;


Let’s take another example of declaring pointers.

int* p1, p2;

Here, we have declared a pointer p1 and a normal variable p2.


Assigning addresses to Pointers

Let’s take an example.

int* pc, c;
c = 5;
pc = &c;

Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.


Get Value of Thing Pointed by Pointers

To get the value of the thing pointed by the pointers, we use the * operator. For example:

int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);   // Output: 5

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc.

Note: In the above example, pc is a pointer, not *pc. You cannot and should not do something like *pc = &c;

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.


Changing Value Pointed by Pointers

Let’s take an example.

int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c);    // Output: 1
printf("%d", *pc);  // Ouptut: 1

We have assigned the address of c to the pc pointer.

Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Let’s take another example.

int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc);  // Ouptut: 1
printf("%d", c);    // Output: 1

We have assigned the address of c to the pc pointer.

Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is the same, c will be equal to 1.

Let’s take one more example.

int* pc, c, d;
c = 5;
d = -15;

pc = &c; printf("%d", *pc); // Output: 5
pc = &d; printf("%d", *pc); // Ouptut: -15

Initially, the address of c is assigned to the pc pointer using pc = &c;. Since c is 5, *pc gives us 5.

Then, the address of d is assigned to the pc pointer using pc = &d;. Since d is -15, *pc gives us -15.


Example: Working of Pointers

Let’s take a working example.

#include <stdio.h>
int main()
{
   int* pc, c;
   
   c = 22;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c);  // 22
   
   pc = &c;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 22
   
   c = 11;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 11
   
   *pc = 2;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c); // 2
   return 0;
}

Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Explanation of the program

  1. int* pc, c;
    A pointer variable and a normal variable is created.
    Here, a pointer pc and a normal variable c, both of type int, is created.
    Since pc and c are not initialized at initially, pointer pc points to either no address or a random address. And, variable c has an address but contains random garbage value.
     
  2. c = 22;
    22 is assigned to variable c.
    This assigns 22 to the variable c. That is, 22 is stored in the memory location of variable c.
     
  3. pc = &c;
    Address of variable c is assigned to pointer pc.
    This assigns the address of variable c to the pointer pc.
     
  4. c = 11;
    11 is assigned to variable c.
    This assigns 11 to variable c.
     
  5. *pc = 2;
    5 is assigned to pointer variable's address.
    This change the value at the memory location pointed by the pointer pc to 2.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c. Then,

int c, *pc;

// pc is address but c is not
pc = c; // Error

// &c is address but *pc is not
*pc = &c; // Error

// both &c and pc are addresses
pc = &c;

// both c and *pc values 
*pc = c;

Here’s an example of pointer syntax beginners often find confusing.

#include <stdio.h>
int main() {
   int c = 5;
   int *p = &c;

   printf("%d", *p);  // 5
   return 0; 
}

Why didn’t we get an error when using int *p = &c;?

It’s because

int *p = &c;

is equivalent to

int *p:
p = &c;

In both cases, we are creating a pointer p (not *p) and assigning &c to it.

To avoid this confusion, we can use the statement like this:

int* p = &c;

Now you know what pointers are, you will learn how pointers are related to arrays in the next tutorial.

C goto statement

In this tutorial, you will learn to create the goto statement in C programming. Also, you will learn when to use a goto statement and when not to use it.

The goto statement allows us to transfer control of the program to the specified label.


Syntax of goto Statement

goto label;
... .. ...
... .. ...
label: 
statement;

The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.

How goto statement works?

Example: goto Statement

// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

   const int maxInput = 100;
   int i;
   double number, average, sum = 0.0;

   for (i = 1; i <= maxInput; ++i) {
      printf("%d. Enter a number: ", i);
      scanf("%lf", &number);
      
      // go to jump if the user enters a negative number
      if (number < 0.0) {
         goto jump;
      }
      sum += number;
   }

jump:
   average = sum / (i - 1);
   printf("Sum = %.2f\n", sum);
   printf("Average = %.2f", average);

   return 0;
}

Output

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53

Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to follow. For example,

one:
for (i = 0; i < number; ++i)
{
    test += i;
    goto two;
}
two: 
if (test > 5) {
  goto three;
}
... .. ...

Also, the goto statement allows you to do bad stuff such as jump out of the scope.

That being said, goto can be useful sometimes. For example: to break from nested loops.


Should you use goto?

If you think the use of goto statement simplifies your program, you can use it. That being said, goto is rarely useful and you can create any C program without using goto altogether.

Here’s a quote from Bjarne Stroustrup, creator of C++, “The fact that ‘goto’ can do anything is exactly why we don’t use it.”

C Recursion

In this tutorial, you will learn to write recursive functions in C programming with the help of an example.

A function that calls itself is known as a recursive function. And, this technique is known as recursion.


How recursion works?

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
How recursion works in C programming?

null

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if…else statement (or similar approach) can be used where one branch makes the recursive call, and other doesn’t.


Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
    int number, result;

    printf("Enter a positive integer: ");
    scanf("%d", &number);

    result = sum(number);

    printf("sum = %d", result);
    return 0;
}

int sum(int n) {
    if (n != 0)
        // sum() function calls itself
        return n + sum(n-1); 
    else
        return n;
}

Output

Enter a positive integer:3
sum = 6

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to the sum() function. This process continues until n is equal to 0.

When n is equal to 0, the if condition fails and the else part is executed returning the sum of integers ultimately to the main() function.

Calculation of sum of natural number using recursion

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is usually much slower.

That being said, recursion is an important concept. It is frequently used in data structure and algorithms. For example, it is common to use recursion in problems such as tree traversal.

C user-defined functions

In this tutorial, you will learn to create user-defined functions in C programming with the help of an example.

A function is a block of code that performs a specific task.

C allows you to define functions according to your need. These functions are known as user-defined functions. For example:

Suppose, you need to create a circle and color it depending upon the radius and color. You can create two functions to solve this problem:

  • createCircle() function
  • color() function

Example: User-defined function

Here is an example to add two integers. To perform this task, we have created an user-defined addNumbers().

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()

{

int n1,n2,sum;

printf("Enters two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;

}

int addNumbers(int a, int b) // function definition

{

int result; result = a+b; return result; // return statement

}


Function prototype

A function prototype is simply the declaration of a function that specifies function’s name, parameters and return type. It doesn’t contain function body.

A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler:

  1. name of the function is addNumbers()
  2. return type of the function is int
  3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before the main() function.


Calling a function

Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, the function call is made using addNumbers(n1, n2); statement inside the main() function.


Function definition

Function definition contains the block of code to perform a specific task. In our example, adding two numbers and returning it.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}

When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.


Passing arguments to a function

In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call.

The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function.

Passing arguments to a function

The type of arguments passed to a function and the formal parameters must match, otherwise, the compiler will throw an error.

If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type.

A function can also be called without passing an argument.


Return Statement

The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after the return statement.

In the above example, the value of the result variable is returned to the main function. The sum variable in the main() function is assigned this value.

Return statement of a function

Syntax of return statement

return (expression);     

For example,

return a;
return (a+b);

C The type of value returned from the function and the return type specified in the function prototype and function definition must match.

C functions

In this tutorial, you will be introduced to functions (both user-defined and standard library functions) in C programming. Also, you will learn why functions are used in programming.

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem:

  • create a circle function
  • create a color function

Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.


Types of function

There are two types of function in C programming:


Standard library functions

The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

  • The printf() is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in the stdio.h header file.
    Hence, to use the printf()function, we need to include the stdio.h header file using #include <stdio.h>.
  • The sqrt() function calculates the square root of a number. The function is defined in the math.h header file.  

Visit standard library functions in C programming to learn more.


User-defined function

You can also create functions as per your need. Such functions created by the user are known as user-defined functions.

How user-defined function works?

#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}

The execution of a C program begins from the main() function.

When the compiler encounters functionName();, control of the program jumps to

 void functionName()

And, the compiler starts executing the codes inside functionName().null

The control of the program jumps back to the main() function once code inside the function definition is executed.

How function works in C programming?

Note, function names are identifiers and should be unique.

This is just an overview of user-defined functions. Visit these pages to learn more on:

  • User-defined Function in C programming
  • Types of user-defined Functions

Advantages of user-defined function

  1. The program will be easier to understand, maintain and debug.
  2. Reusable codes that can be used in other programs
  3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.

C Keywords and identifiers

In this tutorial, you will learn about keywords; reserved words in C programming that are part of the syntax. Also, you will learn about identifiers and how to name them.

Character set

A character set is a set of alphabets, letters and some special characters that are valid in C language.

Alphabets

Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z

C accepts both lowercase and uppercase alphabets as variables and functions.

Digits

0 1 2 3 4 5 6 7 8 9

Special Characters

,<>._
();$:
%[]#?
&{}
^!*/|
\~+ 

White space Characters

Blank space, newline, horizontal tab, carriage, return and form feed.


C Keywords

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:

int money;

Here, int is a keyword that indicates money is a variable of type int (integer).

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords allowed in ANSI C.

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
continueforsignedvoid
doifstaticwhile
defaultgotosizeofvolatile
constfloatshortunsigned

All these keywords, their syntax, and application will be discussed in their respective topics. However, if you want a brief overview of these keywords without going further, visit List of all keywords in C programming.


C Identifiers

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program. For example:

int money;
double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.


Rules for naming identifiers

  1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
  2. The first letter of an identifier should be either a letter or an underscore.
  3. You cannot use keywords as identifiers.
  4. There is no rule on how long an identifier can be. However, you may run into problems in some compilers if the identifier is longer than 31 characters.

You can choose any name as an identifier if you follow the above rule, however, give meaningful names to identifiers that make sense. 

C Variables,constant and literals

In this tutorial, you will learn about variables and rules for naming a variable. You will also learn about different literals in C

Variables

In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. For example:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.

The value of a variable can be changed, hence the name variable.

char ch = 'a';
// some code
ch = 'l';

Rules for naming a variable

  1. A variable name can only have letters (both uppercase and lowercase letters), digits and underscore.
  2. The first letter of a variable should be either a letter or an underscore.
  3. There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.

Note: You should always try to give meaningful names to variables. For example: firstName is a better variable name than fn.

C is a strongly typed language. This means that the variable type cannot be changed once it is declared. For example:

int number = 5;      // integer variable
number = 5.5;        // error
double number;       // error

Here, the type of number variable is int. You cannot assign a floating-point (decimal) value 5.5 to this variable. Also, you cannot redefine the data type of the variable to double. By the way, to store the decimal values in C, you need to declare its type to either double or float.


Literals

Literals are data used for representing fixed values. They can be used directly in the code. For example: 12.5‘c’ etc.

Here, 12.5 and ‘c’ are literals. Why? You cannot assign different values to these terms.


1. Integers

An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming:

  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0, and hexadecimal starts with a 0x.


2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example:

-2.0
0.0000234
-0.22E-5

Note: E-5 = 10-5


3. Characters

A character literal is created by enclosing a single character inside single quotation marks. For example: ‘a’‘m’‘F’‘2’‘}’ etc.


4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc.

In order to use these characters, escape sequences are used.

Escape SequencesCharacter
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null character

For example: \n is used for a newline. The backslash \ causes escape from the normal way the characters are handled by the compiler.


5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For example:

"good"                  //string constant
""                     //null string constant
"      "               //string constant of six white space
"x"                    //string constant having a single character.
"Earth is round\n"         //prints string with a newline

Constants

If you want to define a variable whose value cannot be changed, you can use the const keyword. This will create a constant. For example,

const double PI = 3.14;

Notice, we have added keyword const.

Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;
PI = 2.9; //Error

C Input &Output (I/O)

In this tutorial, you will learn to use scanf() function to take input from the user, and printf() function to display output to the user.

C Output

In C programming, printf() is one of the main output function. The function sends formatted output to the screen. For example,


Example 1: C Output

#include <stdio.h>    
int main()
{ 
    // Displays the string inside quotations
    printf("C Programming");
    return 0;
}

Output

C Programming

How does this program work?

  • All valid C programs must contain the main() function. The code execution begins from the start of the main() function.
  • The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations.
  • To use printf() in our program, we need to include stdio.h header file using the #include <stdio.h> statement.
  • The return 0; statement inside the main() function is the “Exit status” of the program. It’s optional.

Example 2: Integer Output

#include <stdio.h>
int main()
{
    int testInteger = 5;
    printf("Number = %d", testInteger);
    return 0;
}

Output

Number = 5

We use %d format specifier to print int types. Here, the %d inside the quotations will be replaced by the value of testInteger.


Example 3: float and double Output

#include <stdio.h>
int main()
{
    float number1 = 13.5;
    double number2 = 12.4;

    printf("number1 = %f\n", number1);
    printf("number2 = %lf", number2);
    return 0;
}

Output

number1 = 13.500000
number2 = 12.400000

To print float, we use %f format specifier. Similarly, we use %lf to print double values.


Example 4: Print Characters

#include <stdio.h>
int main()
{
    char chr = 'a';    
    printf("character = %c.", chr);  
    return 0;
} 

Output

character = a

To print char, we use %c format specifier.


C Input

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.


Example 5: Integer Input/Output

#include <stdio.h>
int main()
{
    int testInteger;
    printf("Enter an integer: ");
    scanf("%d", &testInteger);  
    printf("Number = %d",testInteger);
    return 0;
}

Output

Enter an integer: 4
Number = 4

Here, we have used %d format specifier inside the scanf() function to take int input from the user. When the user enters an integer, it is stored in the testInteger variable.

Notice, that we have used &testInteger inside scanf(). It is because &testInteger gets the address of testInteger, and the value entered by the user is stored in that address.


Example 6: Float and Double Input/Output

#include <stdio.h>
int main()
{
    float num1;
    double num2;

    printf("Enter a number: ");
    scanf("%f", &num1);
    printf("Enter another number: ");
    scanf("%lf", &num2);

    printf("num1 = %f\n", num1);
    printf("num2 = %lf", num2);

    return 0;
}

Output

Enter a number: 12.523
Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000

We use %f and %lf format specifier for float and double respectively.


Example 7: C Character I/O

#include <stdio.h>
int main()
{
    char chr;
    printf("Enter a character: ");
    scanf("%c",&chr);     
    printf("You entered %c.", chr);  
    return 0;
}   

Output

Enter a character: g
You entered g.

When a character is entered by the user in the above program, the character itself is not stored. Instead, an integer value (ASCII value) is stored.

And when we display that value using %c text format, the entered character is displayed. If we use %d to display the character, it’s ASCII value is printed.


Example 8: ASCII Value

#include <stdio.h>
int main()
{
    char chr;
    printf("Enter a character: ");
    scanf("%c", &chr);     

    // When %c is used, a character is displayed
    printf("You entered %c.\n",chr);  

    // When %d is used, ASCII value is displayed
    printf("ASCII value is % d.", chr);  
    return 0;
}

Output

Enter a character: g
You entered g.
ASCII value is 103.

I/O Multiple Values

Here’s how you can take multiple inputs from the user and display them.

#include <stdio.h>
int main()
{
    int a;
    float b;

    printf("Enter integer and then a float: ");
  
    // Taking multiple inputs
    scanf("%d%f", &a, &b);

    printf("You entered %d and %f", a, b);  
    return 0;
}

Output

Enter integer and then a float: -3
3.4
You entered -3 and 3.400000

Format Specifiers for I/O

As you can see from the above examples, we use

  • %d for int
  • %f for float
  • %lf for double
  • %c for char

Here’s a list of commonly used C data types and their format specifiers.

Data TypeFormat Specifier
int%d
char%c
float%f
double%lf
short int%hd
unsigned int%u
long int%li
long long int%lli
unsigned long int%lu
unsigned long long int%llu
signed char%c
unsigned char%c
long double%Lf

C Operators

In this tutorial, you will learn about different operators in C programming with the help of examples.

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

C has a wide range of operators to perform various operations.


C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).

OperatorMeaning of Operator
+addition or unary plus
subtraction or unary minus
*multiplication
/division
%remainder after division (modulo division)

Example 1: Arithmetic Operators

// Working of arithmetic operators
#include <stdio.h>
int main()
{
    int a = 9,b = 4, c;
    
    c = a+b;
    printf("a+b = %d \n",c);
    c = a-b;
    printf("a-b = %d \n",c);
    c = a*b;
    printf("a*b = %d \n",c);
    c = a/b;
    printf("a/b = %d \n",c);
    c = a%b;
    printf("Remainder when a divided by b = %d \n",c);
    
    return 0;
}

Output

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

The operators +- and * computes addition, subtraction, and multiplication respectively as you might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25.

The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be used with integers.

Suppose a = 5.0b = 2.0c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number
a/b = 2.5  
a/d = 2.5  
c/b = 2.5  

// Both operands are integers
c/d = 2

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

// Working of increment and decrement operators
#include <stdio.h>
int main()
{
    int a = 10, b = 100;
    float c = 10.5, d = 100.5;

    printf("++a = %d \n", ++a);
    printf("--b = %d \n", --b);
    printf("++c = %f \n", ++c);
    printf("--d = %f \n", --d);

    return 0;
}

Output

++a = 11
--b = 99
++c = 11.500000
++d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a--. Visit this page to learn more about how increment and decrement operators work when used as postfix.


C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

OperatorExampleSame as
=a = ba = b
+=a += ba = a+b
-=a -= ba = a-b
*=a *= ba = a*b
/=a /= ba = a/b
%=a %= ba = a%b

Example 3: Assignment Operators

// Working of assignment operators
#include <stdio.h>
int main()
{
    int a = 5, c;

    c = a;      // c is 5
    printf("c = %d\n", c);
    c += a;     // c is 10 
    printf("c = %d\n", c);
    c -= a;     // c is 5
    printf("c = %d\n", c);
    c *= a;     // c is 25
    printf("c = %d\n", c);
    c /= a;     // c is 5
    printf("c = %d\n", c);
    c %= a;     // c = 0
    printf("c = %d\n", c);

    return 0;
}

Output

c = 5 
c = 10 
c = 5 
c = 25 
c = 5 
c = 0

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

OperatorMeaning of OperatorExample
==Equal to5 == 3 is evaluated to 0
>Greater than5 > 3 is evaluated to 1
<Less than5 < 3 is evaluated to 0
!=Not equal to5 != 3 is evaluated to 1
>=Greater than or equal to5 >= 3 is evaluated to 1
<=Less than or equal to5 <= 3 is evaluated to 0

Example 4: Relational Operators

// Working of relational operators
#include <stdio.h>
int main()
{
    int a = 5, b = 5, c = 10;

    printf("%d == %d is %d \n", a, b, a == b);
    printf("%d == %d is %d \n", a, c, a == c);
    printf("%d > %d is %d \n", a, b, a > b);
    printf("%d > %d is %d \n", a, c, a > c);
    printf("%d < %d is %d \n", a, b, a < b);
    printf("%d < %d is %d \n", a, c, a < c);
    printf("%d != %d is %d \n", a, b, a != b);
    printf("%d != %d is %d \n", a, c, a != c);
    printf("%d >= %d is %d \n", a, b, a >= b);
    printf("%d >= %d is %d \n", a, c, a >= c);
    printf("%d <= %d is %d \n", a, b, a <= b);
    printf("%d <= %d is %d \n", a, c, a <= c);

    return 0;
}

Output

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1 

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.

OperatorMeaningExample
&&Logical AND. True only if all operands are trueIf c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0.
||Logical OR. True only if either one operand is trueIf c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1.
!Logical NOT. True only if the operand is 0If c = 5 then, expression !(c==5) equals to 0.

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>
int main()
{
    int a = 5, b = 5, c = 10, result;

    result = (a == b) && (c > b);
    printf("(a == b) && (c > b) is %d \n", result);
    result = (a == b) && (c < b);
    printf("(a == b) && (c < b) is %d \n", result);
    result = (a == b) || (c < b);
    printf("(a == b) || (c < b) is %d \n", result);
    result = (a != b) || (c < b);
    printf("(a != b) || (c < b) is %d \n", result);
    result = !(a != b);
    printf("!(a == b) is %d \n", result);
    result = !(a == b);
    printf("!(a == b) is %d \n", result);

    return 0;
}

Output

(a == b) && (c > b) is 1 
(a == b) && (c < b) is 0 
(a == b) || (c < b) is 1 
(a != b) || (c < b) is 0 
!(a != b) is 1 
!(a == b) is 0 

Explanation of logical operator program

  • (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

OperatorsMeaning of operators
&Bitwise AND
|Bitwise OR
^Bitwise exclusive OR
~Bitwise complement
<<Shift left
>>Shift right

Visit bitwise operator in C to learn more.

Other Operators


Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

Example 6: sizeof Operator

#include <stdio.h>
int main()
{
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%lu bytes\n",sizeof(a));
    printf("Size of float=%lu bytes\n",sizeof(b));
    printf("Size of double=%lu bytes\n",sizeof(c));
    printf("Size of char=%lu byte\n",sizeof(d));

    return 0;
}

Output

Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Other operators such as ternary operator ?:, reference operator &, dereference operator * and member selection operator -> will be discussed in later tutorials.

C if and if else Statements

In this tutorial, you will learn about if statement (including if…else and nested if..else) in C programming with the help of examples.

C if Statement

The syntax of the if statement in C programming is:

if (test expression) 
{
   // statements to be executed if the test expression is true
}

How if statement works?

The if statement evaluates the test expression inside the parenthesis ().

  • If the test expression is evaluated to true, statements inside the body of if are executed.
  • If the test expression is evaluated to false, statements inside the body of if are not executed.
How if statement works in C programming?

To learn more about when test expression is evaluated to true (non-zero value) and false (0), check relational and logical operators.


Example 1: if statement

// Program to display a number if it is negative

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

    printf("Enter an integer: ");
    scanf("%d", &number);

    // true if number is less than 0
    if (number < 0) {
        printf("You entered %d.\n", number);
    }

    printf("The if statement is easy.");

    return 0;
}

Output 1

Enter an integer: -2
You entered -2.
The if statement is easy.

When the user enters -2, the test expression number<0 is evaluated to true. Hence, You entered -2 is displayed on the screen.

Output 2

Enter an integer: 5
The if statement is easy.

When the user enters 5, the test expression number<0 is evaluated to false and the statement inside the body of if is not executed


C if…else Statement

The if statement may have an optional else block. The syntax of the if..else statement is:

if (test expression) {
    // statements to be executed if the test expression is true
}
else {
    // statements to be executed if the test expression is false
}

How if…else statement works?

If the test expression is evaluated to true,

  • statements inside the body of if are executed.
  • statements inside the body of else are skipped from execution.

If the test expression is evaluated to false,

  • statements inside the body of else are executed
  • statements inside the body of if are skipped from execution.
How if...else statement works in C programming?

Example 2: if…else statement

// Check whether an integer is odd or even

#include <stdio.h>
int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);

    // True if the remainder is 0
    if  (number%2 == 0) {
        printf("%d is an even integer.",number);
    }
    else {
        printf("%d is an odd integer.",number);
    }

    return 0;
}

Output

Enter an integer: 7
7 is an odd integer.

When the user enters 7, the test expression number%2==0 is evaluated to false. Hence, the statement inside the body of else is executed.


C if…else Ladder

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The if…else ladder allows you to check between multiple test expressions and execute different statements.


Syntax of if…else Ladder

if (test expression1) {
   // statement(s)
}
else if(test expression2) {
   // statement(s)
}
else if (test expression3) {
   // statement(s)
}
.
.
else {
   // statement(s)
}

Example 3: C if…else Ladder

// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);

    //checks if the two integers are equal.
    if(number1 == number2) {
        printf("Result: %d = %d",number1,number2);
    }

    //checks if number1 is greater than number2.
    else if (number1 > number2) {
        printf("Result: %d > %d", number1, number2);
    }

    //checks if both test expressions are false
    else {
        printf("Result: %d < %d",number1, number2);
    }

    return 0;
}

Output

Enter two integers: 12
23
Result: 12 < 23

Nested if…else

It is possible to include an if...else statement inside the body of another if...else statement.


Example 4: Nested if…else

This program given below relates two integers using either <> and = similar to the if...else ladder’s example. However, we will use a nested if...else statement to solve this problem.

#include <stdio.h>
int main() {
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);

    if (number1 >= number2) {
      if (number1 == number2) {
        printf("Result: %d = %d",number1,number2);
      }
      else {
        printf("Result: %d > %d", number1, number2);
      }
    }
    else {
        printf("Result: %d < %d",number1, number2);
    }

    return 0;
}

If the body of an if...else statement has only one statement, you do not need to use brackets {}.

For example, this code

if (a > b) {
    print("Hello");
}
print("Hi");

is equivalent to

if (a > b)
    print("Hello");
print("Hi");