Table of contents
1.
Introduction
1.1.
C
2.
Tokens in C
2.1.
Example
2.2.
C
3.
Semicolons in C
3.1.
C
4.
Preprocessor Directives in C
4.1.
C
5.
Identifiers in C
5.1.
Example
5.2.
C
6.
C Keywords
6.1.
Example
6.2.
C
7.
Comments in C
7.1.
Example
7.2.
C
8.
Whitespaces in C
8.1.
Example
8.2.
C
9.
Functions in C
9.1.
Function Syntax
9.2.
Example
9.3.
C
9.4.
Importance of Functions
10.
Frequently Asked Questions
10.1.
What is the purpose of the #include directive in C?
10.2.
Can functions in C return more than one value?
10.3.
Why is recursion used in the factorial function example?
11.
Conclusion
Last Updated: Jun 3, 2024
Easy

c syntax

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

C programming is basic and important language for any new programmer who have just started his coding journey. Just like every other language we write or speak which has it’s rules,grammar etc, C also has it’s syntax. Syntax is something which defines the rules and structures. It is a crucial part in learning any computer programming language, without understanding this properly, we cant even write a single program. 

c syntax

In this article we will learn the basics of C syntax, including the structure of a C program and various elements like tokens and identifiers, and how to use comments effectively. 

Basic Syntax Structure of a C Program

Every C program is built using a defined structure that ensures it executes properly from start to finish. A basic C program consists of one or more functions that tell the computer what tasks to perform. The most crucial function in any C program is main(), which is the starting point for execution.

A basic C program structure looks like this:

  1. Header Files Inclusion: The program starts with the inclusion of header files, which contain information and definitions of functions and constants used in the program. For example, #include <stdio.h> allows you to use functions like printf() for output.
     
  2. Function Declarations: Here, you declare the functions that you will use later in your program.
     
  3. Global Variables: Variables that are accessible from any part of the program are defined next.
     
  4. Functions: The program will have one or more functions. Each function has a specific task, like calculating a value or printing a message.
     
  5. Main Function: This function is essential, as it's where your program starts running. Inside main(), you'll write the code that dictates the flow of your program.

Here’s a simple example of what a basic C program might look like:

  • C

C

#include <stdio.h>  // Include the Standard Input Output header file

// Main function where the execution of program begins

int main() {

   printf("Hello, world!\n");  // Prints Hello, world! on the screen

   return 0;  // Terminates the main function

}
You can also try this code with Online C Compiler
Run Code

Output

Hello, world!


In this example, the #include <stdio.h> line tells the compiler to include the standard input-output library, which is used for functions like printf(). The main() function then uses printf() to display "Hello, world!" on the screen.

Tokens in C

Tokens are the smallest elements in a C program, similar to words in a language. Every program you write in C is made up of tokens. They can be keywords, identifiers, constants, strings, symbols, or operators. Understanding these tokens is crucial for writing effective C code because they form the basic building blocks of the language.

There are several types of tokens in C:

  1. Keywords: These are reserved words that have a special meaning in C. For example, int, return, if, and while are all keywords. You cannot use these as names for variables or functions.
     
  2. Identifiers: These are names you give to variables, functions, arrays, etc. Identifiers must start with a letter or an underscore (_) and can be followed by letters, digits, or underscores.
     
  3. Constants: These are fixed values in your code. They can be numeric constants like 1, 100, 3.14, or character constants like 'a', '1'.
     
  4. Strings: A string is a sequence of characters enclosed in double quotes. For example, "Hello, world!".
     
  5. Operators: These are symbols that perform operations on variables and values. For example, + for addition, - for subtraction, and * for multiplication.
     
  6. Special Symbols: These include symbols like semicolons (;), commas (,), and parentheses (()). These symbols help define the structure of the program.

Example

  • C

C

#include <stdio.h>  // include directive is a special symbol

int main() {  // 'int' and 'main' are keywords, 'main' is also an identifier

   int number = 10;  // 'int' is a keyword, 'number' is an identifier, '10' is a constant

   printf("Number is %d", number);  // 'printf' is an identifier, "Number is %d" is a string

   return 0;  // 'return' is a keyword, '0' is a constant

}
You can also try this code with Online C Compiler
Run Code

Output

Number is 10


In this code, int, return, main, and printf are used as part of the syntax to create a functioning program. Each element plays a role in how the program is structured and executed.

Semicolons in C

Semicolons play a critical role in C programming; they act as statement terminators. This means that each statement in a C program must end with a semicolon. It signals to the compiler that the end of one logical statement has been reached, and anything following it will be treated as a new statement.

Consider the semicolon as a period in a sentence: just as a period marks the end of a sentence in English, a semicolon marks the end of a statement in C. This use of semicolons helps maintain clear and organized code, ensuring that each command is properly separated and understood by the compiler.

Here’s how semicolons are used in a simple C program:

  • C

C

#include <stdio.h>  // Header inclusion

int main() {

   int a = 5;  // Variable declaration and initialization

   int b = 15;  // Another variable declaration and initialization

   int sum = a + b;  // Addition operation

   printf("The sum is: %d", sum);  // Print the result

   return 0;  // End of the main function

}
You can also try this code with Online C Compiler
Run Code

Output

The sum is: 20


In this example:

  • int a = 5; declares an integer a and initializes it with the value 5. The semicolon indicates the end of this declaration.
     
  • int sum = a + b; calculates the sum of a and b, and the semicolon concludes this operation.
     
  • The printf statement outputs the sum to the console, and the semicolon ends this output command.
     

Note : Missing a semicolon can lead to compilation errors, as the compiler may struggle to understand where one statement ends and another begins. Therefore, it’s important to check that each statement in your code ends with a semicolon to avoid syntax errors.

Preprocessor Directives in C

Preprocessor directives are instructions that are processed by the compiler before the actual compilation of the code begins. These directives provide the compiler with specific commands, like including other files or defining constants, which help in organizing and managing the code efficiently. The directives are marked by a hash symbol (#).

Here are a few common preprocessor directives used in C:

  1. #include: This directive tells the compiler to include a file into the program. For example, #include <stdio.h> includes the standard input-output library which contains necessary functions for input and output operations.
     
  2. #define: It is used to define constants or macros that are replaced by their values throughout the program. For instance, #define PI 3.14 allows you to use PI in your code, which will be replaced by 3.14 during the compilation.
     
  3. #ifdef, #ifndef, #endif: These conditional directives are used to compile a specific part of the code only if certain conditions are met. This is useful for including code that should only be compiled in specific environments or configurations.
     

Here’s an example which shows how these directives might be used:

  • C

C

#include <stdio.h>  // Includes the Standard Input Output library

#define MAX 100 // Defines a macro for maximum value

int main() {
for (int i = 0; i < MAX; i++) {
printf("%d ", i); // Prints numbers from 0 to 99
}
return 0; // Terminates the main function
}
You can also try this code with Online C Compiler
Run Code

Output

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 


In this code:

  • #include <stdio.h> includes the library required for output functions.
     
  • #define MAX 100 sets up a macro MAX which is used as the limit in the loop, enhancing readability and making the loop condition clearer.
     

Note : Using preprocessor directives effectively can make your code more flexible and easier to maintain. It lets you make changes easily, such as updating a constant defined with #define, which automatically updates everywhere it’s used in your code.

Identifiers in C

Identifiers are the names you assign to various elements such as variables, functions, arrays, and other user-defined items in C programming. Choosing meaningful and descriptive names as identifiers helps make your code more understandable and maintainable.

Rules for naming identifiers in C:

  1. Start with a Letter or an Underscore: Identifiers should begin with either a letter (a-z, A-Z) or an underscore (_). For example, total, _count.
     
  2. Followed by Letters, Digits, or Underscores: After the first character, you can use any combination of letters, digits (0-9), and underscores. For example, total123, num1.
     
  3. Case Sensitive: C is case-sensitive, which means total, Total, and TOTAL are considered different identifiers.
     
  4. Avoid Reserved Keywords: Identifiers cannot be the same as C keywords like int, return, or for.

Example

  • C

C

#include <stdio.h>

int main() {

   int totalAmount = 0;  // 'totalAmount' is an identifier for an integer variable

   int itemCount = 10;  // 'itemCount' is another identifier

   totalAmount = itemCount * 100;  // Assigns value to 'totalAmount'

 printf("Total Amount: %d", totalAmount);  // Displays the total amount

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Total Amount: 1000

In this code:

  • totalAmount and itemCount are identifiers used to store integer values.
     
  • These names are chosen to clearly indicate what they represent, making the code easier to read and understand.
     

Note : Using clear and descriptive identifiers makes your code much easier to follow, which is especially useful when you or someone else returns to your code after some time. It helps in debugging and maintaining the code without confusion.

C Keywords

Keywords in C are reserved words that have special meanings. These words are part of the C language syntax, and you cannot use them as identifiers for variables, functions, or any other user-defined item because they serve specific purposes in the language.

Here are some characteristics and common uses of C keywords:

  • Fixed Meaning: Each keyword has a fixed meaning in C programming, which cannot be changed or altered.
     
  • Control Structures: Many keywords, like if, else, while, and for, are used to control the flow of the program.
     
  • Data Types: Keywords such as int, char, float, and double are used to declare variables of different types.
     
  • Function Specifiers: Words like return signal the return of a value from a function.

Example

  • C

C

#include <stdio.h>

int main() {

   int number = 10;  // 'int' declares a variable of type integer

   if (number > 0) {  // 'if' starts a conditional statement

       printf("The number is positive.\n");  // 'printf' is a function used for output

   }

   return 0;  // 'return' exits the function

}
You can also try this code with Online C Compiler
Run Code

Output

The number is positive.


In this example:

  • int is used to declare an integer variable named number.
     
  • if checks whether the number is greater than zero.
     
  • return provides a way to exit the main function, which is required in every main function to return control back to the operating system.

Comments in C

Comments in C are notes that programmers add to their code to make it easier to understand. They are not executed by the compiler, meaning they do not affect how a program runs. Instead, comments help explain what the code does, making it easier for someone (including the person who wrote it) to follow the program's logic later.

There are two main types of comments in C:

  • Single-line Comments: These start with // and extend to the end of the line. Use them for brief explanations or notes right next to code.
     
  • Multi-line Comments: These start with /* and end with */. They can span multiple lines and are useful for longer descriptions or for temporarily disabling parts of the code during testing.

Example

  • C

C

#include <stdio.h>

int main() {
// Calculate the sum of two numbers
int num1 = 10; // first number
int num2 = 20; // second number
int sum = num1 + num2; // sum of num1 and num2

/*
The printf function below prints the sum.
You can change the text to modify what's printed.
*/
printf("Sum is: %d", sum); // Output the sum

return 0; // End of main function
}
You can also try this code with Online C Compiler
Run Code

Output

Sum is: 30


In this code:

  • Single-line comments (//) are used to describe what each line does.
     
  • A multi-line comment (/* ... */) explains a section of the code, in this case, the use of the printf function.

Note : Comments make your code more readable and maintainable. They are especially valuable in complex projects or when working in teams, as they convey the message any person would like to leave for another teammate without affecting the performance of the code.

Whitespaces in C

Whitespaces in C are characters that create empty space in your code. They include spaces, tabs, and newlines. While these characters don't affect how your program runs, they are crucial for organizing and structuring your code to make it readable.

The main uses of whitespaces in C are:

  1. Separating Tokens: Whitespaces are used to separate tokens (like keywords, identifiers, and operators) from each other. For example, in int age = 25;, spaces separate int, age, =, and 25 to make the statement clear.
     
  2. Indenting Code: Proper indentation, usually with spaces or tabs, helps visually organize code, making it easier to follow the logical structure of your program. It's common to indent code blocks within functions, loops, and conditionals to highlight their hierarchy.

Example

  • C

C

#include <stdio.h>

int main() {
int a = 5; // Assignment with spaces for clarity
int b = 10;

if (a < b) { // Condition clearly separated by spaces
printf("a is less than b\n"); // Statement inside if block is indented
}

for (int i = 0; i < 10; i++) { // Loop with spaces separating operators
printf("%d ", i); // Indented to show it's inside the for loop
}

return 0; // End of main function
}
You can also try this code with Online C Compiler
Run Code

Output

a is less than b
0 1 2 3 4 5 6 7 8 9


In this program:

  • Spaces separate keywords, identifiers, and operators making the code easier to read.
     
  • Indentation highlights the blocks of code within if and for statements, helping you understand the flow and scope of the program.
     

Proper use of whitespaces contributes significantly to the readability of your code, which is essential for both solo and team coding efforts. It helps others (and future you) to quickly understand and navigate the code.

Functions in C

Functions in C are blocks of code that perform specific tasks and can be reused throughout your program. Defining functions helps you avoid repetition, making your code more organized and manageable. Each function in C is declared with a type, which indicates the type of value the function returns to the part of the program that called it.

Function Syntax

The basic syntax for a function in C includes the return type, the function name, and a set of parentheses that may include parameters (also known as arguments). Here’s the general structure:

return_type function_name(parameters) {
    // Code to execute
    return value; // Optional based on return type
}

Example

Let's look at a simple example to illustrate how functions are used:

  • C

C

#include <stdio.h>

// Function declaration

int multiplyTwoNumbers(int x, int y);

int main() {

   int result = multiplyTwoNumbers(10, 5); // Function call

   printf("The result is: %d\n", result);

   return 0;

}

// Function definition

int multiplyTwoNumbers(int x, int y) {

   return x * y; // Returns the product of x and y

}
You can also try this code with Online C Compiler
Run Code

Output

The result is: 50


In this example:

  1. Function Declaration: The function multiplyTwoNumbers is declared at the beginning. This tells the compiler about the function's return type and parameters, preparing it to recognize the function when it's used in main().
     
  2. Function Call: Inside the main() function, multiplyTwoNumbers is called with two arguments (10 and 5), and the returned value is stored in result.
     
  3. Function Definition: The definition of multiplyTwoNumbers follows main(). This includes the actual code that executes when the function is called. It multiplies the inputs x and y and returns the result.

Importance of Functions

  1. Modular: By breaking down tasks into separate functions, you make your program modular, which simplifies testing and debugging.
     
  2. Reusable: Functions can be reused across different parts of a program or even in different programs.
     
  3. Organized: Functions help keep your code organized and focused on specific tasks.

Frequently Asked Questions

What is the purpose of the #include directive in C?

The #include directive is used to include the contents of a standard or user-defined header file in a C program. This is necessary for accessing predefined functions and constants, such as those in the stdio.h library for input and output operations.

Can functions in C return more than one value?

While a function in C can only return one value directly, it can return multiple values indirectly by using pointers or by returning a struct.

Why is recursion used in the factorial function example?

Recursion simplifies the coding of a function that can be divided into smaller, similar subproblems. It is particularly useful for tasks like calculating factorials, where the operation to find n! can be expressed as n * (n-1)!.

Conclusion

In this article, we have learned the fundamentals of C syntax, which includes the basic structure of a C program, the role of tokens, the importance of semicolons, how preprocessor directives function, and the use of identifiers and keywords. We also discussed the significance of comments for code clarity and the necessity of whitespaces for readability. Apart from all these we saw how functions are defined and used. All these are very important part of syntax. We need to understand their usage properly before going to complex part of programming.

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 andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass