Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

What are keywords in C?

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

When you start learning to program with C, you'll come across special words that the language already understands. These are called 'keywords', and they help you give instructions to the computer in a way it can understand. Think of them as the basic commands you need to know to tell the computer what to do. 

Keywords in C

In this article, we'll see what these keywords are, why they're important, and how to use them in your code. From setting up variables to making decisions in your program, we'll cover it all, step by step.

What are Keywords?

In C programming, keywords act as the main tools that help shape our code. These are not just any words; they are reserved terms that the C language has given special meanings to. Imagine you're learning a new language where certain words have the power to perform specific actions. In C, these powerful words are the keywords. They're like the fixed rules you need to follow to communicate effectively with the computer.

Keywords are the most important part of C programming. They tell the compiler what operations to perform. Operations can range from basic tasks like declaring variables, to more complex ones like controlling the flow of the program with conditions and loops. Each keyword is a command that the C language understands right out of the box, and there are about 32 of them in standard C. You'll see keywords for doing all sorts of things, like defining the type of data you're working with (int, char, float), controlling the flow of your program (if, else, while, for), or even managing the visibility and lifetime of your variables (static, extern).

One thing to remember is that because these words are reserved, you can't use them as names for your variables or functions. Trying to name a variable int or for would confuse the compiler because it expects these words to play their predefined roles in the language.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

auto

The auto keyword in C is used to declare variables that are automatically stored in memory. This means that the variable is stored in a place called the stack, and it can be used within the function it's declared in. Nowadays, we don't really need to use auto because all variables we declare inside functions are automatic by default. But it's still good to know what it does.

Let's see auto in action with a simple example:

  • C

C

#include <stdio.h>

void myFunction() {
auto int myNumber = 10; // Using 'auto' to declare an integer
printf("The number is: %d\n", myNumber);
}

int main() {
myFunction(); // Calling the function to see 'auto' in action
return 0;
}

Output

The number is: 10


When you run this code, it will print out "The number is: 10". Here, auto int myNumber = 10; declares an automatic integer variable named myNumber and initializes it with the value 10. The printf function then uses this variable to display its value. Even though we used auto, you can see that it works just like any normal variable declaration.

Break & Continue


In C programming, break and continue are keywords used to control the flow of loops. Loops repeat a block of code, but sometimes you might want to stop the loop early or skip part of the loop under certain conditions. That's where break and continue come in.

  • break is used to exit a loop completely. When the program hits a break statement, it stops the loop and moves on to the code that comes after the loop.
     
  • continue is used to skip the rest of the loop and start the next iteration. When the program hits a continue statement, it jumps back to the beginning of the loop for the next round of execution.
     

Here's an example that uses both break and continue:

  • C

C

#include <stdio.h>

int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Stop the loop when i is 5
}
if (i == 3) {
continue; // Skip the rest of the loop when i is 3
}
printf("%d ", i); // Print the value of i
}
return 0;
}

Output

0 1 2 4


In this example, the loop is supposed to run from 0 to 9. But because of the break statement, the loop stops completely when i reaches 5. So, it never gets a chance to print numbers 5 through 9. The continue statement causes the loop to skip printing the number 3. So, the output will be "0 1 2 4".

switch, case, and default


The switch statement in C is a type of conditional statement that lets you choose between multiple options. It's like making a decision based on different cases. Inside a switch, you'll find case statements. Each case represents a possible scenario or choice. If none of the cases match, the default section is executed.

Here's how you can use switch, case, and default in a program:

  • C

C

#include <stdio.h>

int main() {
int choice = 2;

switch (choice) {
case 1:
printf("You chose option 1.\n");
break;
case 2:
printf("You chose option 2.\n");
break;
case 3:
printf("You chose option 3.\n");
break;
default:
printf("Invalid choice.\n");
}

return 0;
}

Output

You chose option 2.


In this example, we have a variable choice set to 2. The switch statement checks the value of choice. Since choice is 2, the program finds the case that matches the number 2 and executes the code inside that case. After printing "You chose option 2.", it hits the break statement and exits the switch. If choice had a value that wasn't 1, 2, or 3, the default section would run, printing "Invalid choice."

Char

The char keyword in C is used to declare character variables. Characters are single letters or symbols, and char lets you store them in your programs. Each char takes up one byte of memory, and you can use them to work with individual characters or strings of characters.

Here's a simple example showing how to use char:

  • C

C

#include <stdio.h>

int main() {
char letter = 'A'; // Declare a char variable and assign it a letter
printf("The letter is: %c\n", letter); // Print the char variable

return 0;
}

Output

The letter is: A


In this code, we declare a char variable named letter and assign it the character 'A'. When we print it using printf, we use %c in the format string to tell printf that we're dealing with a character. The output of this program will be "The letter is: A".

Characters are fundamental in C programming, especially when you start working with text and strings.

Const

The const keyword in C is used to declare variables whose values cannot be changed once they have been assigned. It stands for "constant", meaning fixed or unchangeable. Using const is a way to make your code safer and more readable, as it prevents accidental changes to values that should remain constant throughout the program.

Here's an example of how to use const:

  • C

C


#include <stdio.h>

int main() {
const int DAYS_IN_A_WEEK = 7; // Declare a constant variable
printf("There are %d days in a week.\n", DAYS_IN_A_WEEK);

// DAYS_IN_A_WEEK = 8; // This line would cause a compile error because you can't change a const variable

return 0;
}

Output

There are 7 days in a week.


In this code, DAYS_IN_A_WEEK is declared as a constant integer with a value of 7. Trying to change this value later in the code would result in a compilation error, ensuring the integrity of this constant value throughout the program.

Do

The do keyword is used in C programming to create a do-while loop. This type of loop will execute a block of code at least once before checking a condition. It's useful when you want to ensure the code runs at least once regardless of whether the condition is true or false initially.

Example of do-while loop:

  • C

C

#include <stdio.h>

int main() {
int count = 1;

do {
printf("Count: %d\n", count); // This code block runs at least once
count++;
} while (count <= 5);

return 0;
}

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5


In this example, the code inside the do block executes, printing the count, and then increments count. After that, the while condition is checked. As long as count is less than or equal to 5, the loop continues. The output will be numbers from 1 to 5.

double and float

double and float are keywords used to declare floating-point variables, which can store numbers with fractional parts (like 3.14). The main difference between them is precision. float is a single-precision floating-point, and double is a double-precision floating-point, meaning double has more precision and can store larger numbers.

Example using float and double:

  • C

C

#include <stdio.h>

int main() {
float pi_float = 3.14f; // Single-precision floating point
double pi_double = 3.141592653589793; // Double-precision floating point

printf("pi_float: %f\n", pi_float);
printf("pi_double: %lf\n", pi_double);

return 0;
}

Output

pi_float: 3.140000
pi_double: 3.141593


This code declares two variables, one float and one double, both representing the mathematical constant pi but with different levels of precision. The output will show the difference in precision between float and double.

If-else

The if-else statement in C is used for decision-making. It executes a block of code if a specified condition is true and another block of code if the condition is false.

Example of if-else:

  • C

C

#include <stdio.h>

int main() {
int number = 10;

if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is not positive.\n");
}

return 0;
}

Output

The number is positive.


In this example, the program checks if number is greater than 0. Since 10 is positive, it prints "The number is positive."

Enum

Enum (short for enumeration) is a keyword used to define a set of named integer constants. It makes the code more readable by allowing you to use meaningful names instead of numbers.

Example of enum:

  • C

C

#include <stdio.h>

enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main() {
enum week today;
today = Wednesday;
printf("Day number of Wednesday is %d.\n", today);

return 0;
}

Output

Day number of Wednesday is 3.


In this example, enum week defines names for the days of the week. Wednesday is assigned to today, and since enum values start from 0 by default, Wednesday represents 3.

Extern

The extern keyword is used to declare a global variable or a function in another file. It tells the compiler that the variable or function is defined in another file, making it accessible to multiple files.

Example of using extern:

// File1.c
#include <stdio.h>

extern int count;  // Declaration of an external variable

void write_extern(void) {
    printf("Count is %d\n", count);
}

// File2.c
#include <stdio.h>

int count = 5;  // Definition of count

void main() {
    write_extern();
}


When File2.c is run, it will print "Count is 5" using the count variable defined in File2.c and accessed in File1.c using extern.

For

The for loop in C is used to repeat a block of code a specified number of times. It's useful for iterating over arrays or executing a set of statements multiple times.

Example of for loop:

  • C

C

#include <stdio.h>

int main() {
for (int i = 0; i < 5; i++) {
printf("i is %d\n", i);
}

return 0;
}

Output

i is 0
i is 1
i is 2
i is 3
i is 4


This loop prints the values of i from 0 to 4, iterating 5 times as defined in the loop conditions.

goto

The goto keyword is used to make an unconditional jump to another part of the program. It's generally recommended to avoid goto as it can make the code less readable and harder to follow.

Example of goto:

  • C

C

#include <stdio.h>

int main() {
int n = 0;
label:
printf("%d ", n);
n++;
if (n < 5) goto label; // Jumps back to the label

return 0;
}

Output

0 1 2 3 4 


This code prints numbers from 0 to 4 using a goto statement to jump back to the label and repeat the loop until n is less than 5.

Int, short, long, signed, and unsigned

These keywords are used to define integer variables of different sizes and properties.

  • int is the basic integer type, with a typical size of 4 bytes, capable of storing values from -2,147,483,648 to 2,147,483,647.
     
  • short is a smaller integer type, usually 2 bytes, with a range from -32,768 to 32,767.
     
  • long is an extended size integer, often 8 bytes on 64-bit systems, with a large range.
     
  • signed and unsigned can modify these types, where signed (the default) allows for positive and negative values, and unsigned allows only non-negative values, effectively doubling the maximum positive value.
     

Example:

  • C

C

#include <stdio.h>

int main() {
int a = 1000;
short b = 500;
long c = 1000000;
unsigned int d = 50000;

printf("int: %d\n", a);
printf("short: %d\n", b);
printf("long: %ld\n", c);
printf("unsigned int: %u\n", d);

return 0;
}

Output

int: 1000
short: 500
long: 1000000
unsigned int: 50000


This example demonstrates declaring variables with different integer types and their respective ranges.

Return

The return keyword is used to exit a function and optionally return a value to the function caller.

Example:

  • C

C

#include <stdio.h>

int add(int x, int y) {
return x + y; // Returns the sum of x and y
}

int main() {
int result = add(5, 3);
printf("The result is: %d\n", result);

return 0;
}

Output

The result is: 8


This code defines a function add that takes two parameters and returns their sum. The main function then calls add and prints the result.

Sizeof

The sizeof operator is used to obtain the size (in bytes) of a data type or a variable.

Example:

  • C

C

#include <stdio.h>

int main() {
int a;
double b;

printf("Size of int: %zu bytes\n", sizeof(a));
printf("Size of double: %zu bytes\n", sizeof(b));

return 0;
}

Output

Size of int: 4 bytes
Size of double: 8 bytes


This example prints the size of an int and a double variable, demonstrating how sizeof can be used to find out how much memory a particular type or variable occupies.

Register

The register keyword is a hint to the compiler that a variable should be stored in a register for faster access. However, modern compilers typically optimize code better than using register.

Example:

  • C

C

#include <stdio.h>

int main() {
register int counter = 0;

for (int i = 0; i < 10000; i++) {
counter++;
}

printf("Counter: %d\n", counter);

return 0;
}

Output


Counter: 10000


This code declares a register variable counter and uses it in a loop, suggesting that counter should be kept in a CPU register for quick access.

Static

The static keyword has multiple uses in C: inside a function, it makes a variable retain its value between function calls; at file level, it restricts the visibility of a function or variable to its file.

Example of static inside a function:

  • C

C

#include <stdio.h>

void function() {
static int count = 0; // This variable retains its value between calls
count++;
printf("Count: %d\n", count);
}

int main() {
function();
function();
function();

return 0;
}

Output

Count: 1
Count: 2
Count: 3


Each call to function will increment and print count, showing that count retains its value between calls.

Struct

The struct keyword defines a structure type, which is a composite data type that can contain variables of different types under a single name. Structures are used to group related data together.

Example of struct:

  • C

C

#include <stdio.h>
#include<string.h>
struct Person {
char name[50];
int age;
};

int main() {
struct Person person1;

// Assigning data to person1 fields
person1.age = 25;
strcpy(person1.name, "John Doe"); // Use strcpy to copy the string

printf("%s is %d years old.\n", person1.name, person1.age);

return 0;
}

Output

John Doe is 25 years old.


This example defines a struct named Person with two fields: name and age. It then creates a Person variable, assigns values to its fields, and prints them.

Typedef

The typedef keyword is used to create a new name (alias) for an existing type. It can make complex types easier to work with and improve code readability.
Example of typedef:

  • C

C

#include <stdio.h>
#include<string.h>
typedef struct {
char name[50];
int age;
} Person;

int main() {
Person person1;

// Assigning data to person1 fields
person1.age = 30;
strcpy(person1.name, "Alice Smith");

printf("%s is %d years old.\n", person1.name, person1.age);

return 0;
}

Output

Alice Smith is 30 years old.


In this example, typedef is used to create an alias Person for a struct, making it unnecessary to use the struct keyword when declaring variables of that type.

Union

A union is similar to a struct in that it's a user-defined type containing multiple members. The key difference is that in a union, all members share the same memory location. This means a union can hold only one of its non-static data members at a time.

Example of union:

  • C

C

#include <stdio.h>
#include<string.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %f\n", data.f);

strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);

// Note: The values of data.i and data.f will be overwritten when data.str is assigned

return 0;
}

Output

data.i: 10
data.f: 220.500000
data.str: C Programming


This example demonstrates that at any point, you can only use one of the members of the union since they overlap in memory.

Void

The void keyword is used to specify that a function doesn't return a value or to declare generic pointers.

Example of void in a function:

  • C

C

#include<string.h>

#include <stdio.h>

void printMessage() {
printf("Hello, World!\n");
}

int main() {
printMessage(); // Call the function

return 0;
}

Output


Hello, World!


In this code, printMessage is a void function, meaning it doesn't return any value.

Volatile

The volatile keyword tells the compiler that a variable's value may change at any time without any action being taken by the code the compiler finds nearby. It's often used in embedded systems programming.

Example of volatile:

#include<string.h>
#include <stdio.h>
int main() {
   volatile int count = 0;  // 'volatile' informs the compiler the value of count can change unexpectedly
   while (count == 0) {
       // Waiting for count to change
   }
   printf("Count changed to %d\n", count);
   return 0;
}


This example shows a volatile variable count. The use of volatile ensures that the compiler won't optimize the loop away, even if it appears that the loop should never exit within the program's code.

Frequently Asked Questions

Can I use switch with float or double in C?

No, you can't use switch with float or double types. The switch statement only works with integer types (like int) and char.

Why should I avoid using goto in my C code?

Using goto can make your code hard to read and follow, leading to "spaghetti code." It's better to use structured loop and control statements like while, for, and if-else.

What's the difference between struct and union?

In a struct, each member has its own storage, so different members can hold different values simultaneously. In a union, all members share the same storage space, so only one member can have a value at a time.

Conclusion

Understanding C keywords is crucial for anyone learning to program in this language. Keywords like int, if-else, and for form the foundation of C programming, allowing you to define variable types, make decisions, and create loops. More advanced keywords like struct, enum, and union let you work with complex data structures, while volatile and extern are essential for specific scenarios like embedded systems and multi-file projects.

Remember, the key to becoming proficient in C programming is not just knowing what these keywords do but also understanding when and how to use them effectively in your code

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
What are Keywords?
3.
auto
3.1.
C
4.
Break & Continue
4.1.
C
5.
switch, case, and default
5.1.
C
6.
Char
6.1.
C
7.
Const
7.1.
C
8.
Do
8.1.
C
9.
double and float
9.1.
C
10.
If-else
10.1.
C
11.
Enum
11.1.
C
12.
Extern
13.
For
13.1.
C
14.
goto
14.1.
C
15.
Int, short, long, signed, and unsigned
15.1.
C
16.
Return
16.1.
C
17.
Sizeof
17.1.
C
18.
Register
18.1.
C
19.
Static
19.1.
C
20.
Struct
20.1.
C
21.
Typedef
21.1.
C
22.
Union
22.1.
C
23.
Void
23.1.
C
24.
Volatile
25.
Frequently Asked Questions
25.1.
Can I use switch with float or double in C?
25.2.
Why should I avoid using goto in my C code?
25.3.
What's the difference between struct and union?
26.
Conclusion