Back to: C Tutorials For Beginners and Professionals
Types of Variables in C Language:
In this article, I am going to discuss the Types of Variables in C Language with Examples. Please read our previous article discussing the basics of C Language Variables. Variables are categorized into three types based on the scope and lifetime of a variable. They are as follows
- Local variable
- Global variable
- Environment variable
Note: The Scope tells about the visibility (i.e., from where this variable is visible), whereas the lifetime tells about the durability (i.e., how much time the value in the variable is valid).
Local Variables in C Language:
The variables declared inside a function are known as Local Variables in C. The scope of local variables in C will be within the function only, i.e., we can’t access a local variable from outside the function in which it is declared. These variables are declared within the function and can’t be accessed outside the function.
The lifetime of a local variable is throughout the function, i.e., memory to the local variables allocated when the function execution started and will become invalid once the function completes its execution.
Example to Understand Local Variables in C Language:
In the following example, m and n variables have scope within the main function only. These are not visible to the test function. Likewise, a and b variables have scope within the test function only. These are not visible to the main function.
include <stdio.h> void test (); int main() { int m = 22, n = 44; // m, n are local variables of main function /*m and n variables are having scope within this main function only. These are not visible to test function.*/ /* If you try to access a and b in this function, you will get 'a' undeclared and 'b' undeclared error */ printf ("\n values : m = %d and n = %d", m, n); test(); } void test() { int a = 50, b = 80; // a, b are local variables of test function /* a and b variables are having scope within this test function only. These are not visible to main function.*/ /* If you try to access m and n in this function, you will get 'm' undeclared and 'n' undeclared error */ printf ("\n values : a = %d and b = %d", a, b); }
Output:
In the C programming language, local variables are those variables that are declared within a function or a block and can only be used within that function or block. Here are some key points about local variables in C:
- Scope: The scope of a local variable is limited to the function or block in which it is declared. It cannot be accessed or used outside of this scope.
- Lifetime: The lifetime of a local variable is limited to the time during which the function is executing. When the function execution is completed, the storage for the local variable is no longer allocated.
- Initialization: Local variables should be initialized before use. If not initialized, they contain garbage values (i.e., random values).
- Declaration: Local variables are declared at the beginning of a function or block.
- Memory Allocation: Memory for local variables is allocated on the stack.
- Recursion: In the case of recursive function calls, each call creates a new set of local variables, distinct from the local variables in other calls of the same function.
- Visibility: Other functions or blocks of code cannot access local variables.
Global Variables in C Language:
The variables which are declared outside the function are known as Global Variables in C. The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.
The lifetime of a global variable is throughout the program, i.e. memory to the global variables will be allocated when the execution of the program is started and will become invalid after finishing the execution of the program.
Example to Understand Global Variables in C:
In the following example, the variables a, b, m, and n are declared outside the scope of any function. So, these variables are visible to the main function and all other sub-functions.
#include<stdio.h> void test(); int m = 22, n = 44; int a = 50, b = 80; int main() { printf("All variables are accessed from main function"); printf("\n values: m=%d: n=%d: a=%d: b=%d", m, n, a, b); test(); } void test() { printf("\n\n All variables are accessed from" \ " test function"); printf("\n values: m=%d: n=%d: a=%d: b=%d", m ,n, a, b); }
Output:
Global variables in C are variables that are declared outside of any function. These variables are accessible from any function within the file they are declared in. If you want to access a global variable in a different file, you must use the extern keyword in the other file to declare the variable. Here are some key points about global variables in C:
- Scope: Global variables are accessible from any function within the same file.
- Lifetime: They are allocated when the program starts and deallocated when the program terminates. This means they retain their value throughout the program’s execution.
- Default Value: If uninitialized, global variables in C are automatically initialized to zero for basic data types like int, float, etc.
- Usage: They are used when multiple functions need to access the same data. However, excessive use of global variables can make the code harder to understand and maintain.
- Declaration: To declare a global variable, you simply declare it outside of any function. For example: int myGlobalVar; // This is a global variable
- Accessing in Other Files: Use the extern keyword to use a global variable in another file. For example, if myGlobalVar is declared in file1.c, you can access it in file2.c like this: extern int myGlobalVar; // Accessing the global variable from file1.c
- Drawbacks: While they are useful in some situations, global variables can lead to code that is difficult to debug and maintain because any part of the program can change its value.
It’s often recommended to limit the use of global variables and prefer passing variables as arguments to functions to maintain better control over the program’s state and behavior.
Environment Variables in C Language:
The environment variable is a variable that will be available for all C applications and C programs. We can access these variables from anywhere in a C program without declaring and initializing them in an application or C program.
In the C programming language, environment variables are a set of dynamic-named values that can affect how running processes behave on a computer. They are part of the environment in which a process runs. For example, an environment variable can store the drive letter and the directory path from which a program was started. To work with environment variables in C, you typically use the following functions from the C standard library:
- getenv(): This function is used to retrieve the value of an environment variable.
- setenv(): This function is used to set or change the value of an environment variable.
- unsetenv(): This function is used to delete an environment variable.
- putenv(): This function adds or changes the value of environment variables.
getenv() Function in C Language
The getenv() function in C is used to retrieve a value from the environment variable list of the current process. The environment variable list is an array of strings representing the environment variables, where each string is of the form key=value. Here’s a basic overview of how getenv() works:
Syntax: char *getenv(const char *name);
name: The name of the environment variable you want to access.
Return Value: If the environment variable is found, getenv() returns a pointer to the value associated with the environment variable name. If the environment variable is not found, it returns NULL.
Usage Example:
#include <stdio.h> #include <stdlib.h> int main() { char *path = getenv("PATH"); if (path != NULL) { printf("PATH: %s\n", path); } else { printf("PATH variable not found.\n"); } return 0; }
This example retrieves the value of the PATH environment variable and prints it. If PATH is not found in the environment, it prints a message indicating that.
Important Notes:
- The string returned by getenv() should not be modified. Modifying it can lead to undefined behavior.
- The pointer returned may point to a static area that can be overwritten by subsequent calls to getenv(), setenv(), or putenv().
- The behavior of getenv() is thread-safe in C11 and later, but in earlier versions, it may not be thread-safe.
Common Use Cases:
- To get system-specific configurations like PATH, HOME, or other custom environment variables set in the system.
- To make programs adaptable to different environments without changing the code.
setenv() Function in C Language
The setenv() function in C language is used for setting or changing the value of an environment variable. Environment variables are a set of dynamic values that can affect how running processes behave on a computer. They are part of the environment in which a process runs. Here’s a brief overview of the setenv() function:
Syntax: int setenv(const char *name, const char *value, int overwrite);
Parameters:
- name: The name of the environment variable.
- value: The new value of the environment variable.
- overwrite: If set to non-zero, the existing value of the environment variable will be overwritten. If set to zero, the value will not be overwritten if the environment variable already exists.
Return Value: On success, it returns zero. On error, it returns a non-zero value, and errno is set appropriately.
setenv() Function Example:
#include <stdlib.h> int main() { if (setenv("MYVAR", "HelloWorld", 1) != 0) { perror("setenv failed"); } else { // MYVAR is now set or updated } // Your code here return 0; }
In this example, the environment variable MYVAR is set (or updated) to “HelloWorld”. If the setenv function fails, an error message is printed. Remember to include the <stdlib.h> header file, as it contains the declaration of the setenv function.
putenv() Function in C Language
The putenv() function in the C programming language is used to change or add a new value to the environment of the calling process. The environment is a collection of strings representing the process’s environment variables, typically including system settings and configuration values. Here’s a brief overview of how putenv() works:
Syntax: The basic syntax of the putenv() function is as follows:
int putenv(char *string);
The function takes a single argument, string, which is a null-terminated string of the form name=value. The name represents the environment variable’s name, and the value is the new value to be assigned to it.
Usage: When you call putenv(), it adds a new variable to the environment or changes the value of an existing variable. If the variable named by name already exists, its value is replaced with value. If it does not exist, a new variable is created with the given name and value.
Return Value: The putenv() function returns zero on success. On error, it returns a non-zero value.
Important Considerations:
- The string passed to putenv() should not be deallocated or modified after the call, as the environment will store a direct pointer to it.
- The behavior of putenv() can vary slightly between different operating systems and C library implementations.
putenv() Function Example:
#include <stdlib.h> int main() { char envVar[] = "MYVAR=123"; putenv(envVar); // Now the environment variable MYVAR is set to 123 return 0; }
Remember that changes made to the environment using putenv() are reflected only in the current process and its children, not in the parent process or any other unrelated processes.
unsetenv() Function in C Language
The unsetenv() function in C is used to delete an environment variable from the current process’s environment. This function is part of the standard library and is typically included in <stdlib.h> header file. The prototype of the unsetenv() function is:
int unsetenv(const char *name);
Here’s a breakdown of how unsetenv() works:
- Parameter: The unsetenv() function takes a single argument, name, which is a string representing the name of the environment variable you want to delete.
- Return Value: The function returns an integer. If the function succeeds in deleting the environment variable, it returns 0. If it fails, for example, if the name is NULL or if the environment variable specified by name does not exist, it returns a non-zero value.
- Usage: It’s important to ensure that the name argument does not contain an ‘=’ character, as it would result in undefined behavior according to the POSIX standard.
- Environment Variables: Environment variables are a key part of the environment in which a process runs. They typically store information such as the file path, user preferences, and system settings. Modifying these variables can alter the behavior of various processes in the system.
- Security Consideration: While manipulating environment variables, it’s crucial to consider the security implications, as incorrect use can lead to vulnerabilities, especially in programs that run with elevated privileges.
Here’s an example of how unsetenv() might be used in a C program:
#include <stdlib.h> #include <stdio.h> int main() { const char *envVar = "TEST_VAR"; // Set an environment variable setenv(envVar, "123", 1); printf("Environment variable %s set to %s\n", envVar, getenv(envVar)); // Unset the environment variable if (unsetenv(envVar) != 0) { perror("Error unsetting environment variable"); return 1; } // Check if the environment variable is successfully unset if (getenv(envVar) == NULL) { printf("Environment variable %s successfully unset\n", envVar); } else { printf("Environment variable %s is still set\n", envVar); } return 0; }
In this example, an environment variable TEST_VAR is first set and then unset. The program checks if TEST_VAR is successfully unset by attempting to retrieve its value with getenv(). If getenv() returns NULL, it indicates that the variable has been successfully removed from the environment.
Interview Questions on Variables in C Programming Language:
Question 1: What will be the output of the below program
#include <stdio.h> int main() { printf("%d", number); int number; return 0; }
Output: Compilation Error. This is because the local variable’s scope starts from the point where we declared. In the above example, we are trying to access the variable before declaring it.
Question 2: What will be the output of the below program?
#include <stdio.h> int main() { int number = 10; int number = 20; printf("%d", number); return 0; }
Output: Compilation Error. This is because Multiple declarations of the local variables with the same name and in the same scope are not allowed. In the above example, we are trying to declare a Local variable with the same name more than once
Question 3: What will be the output of the below program?
#include <stdio.h> int main() { printf("%d", number); return 0; } int number = 10;
Output: undeclared variable error. This is because the scope of the global variable also starts from the point where it is declared. In the above example, we are declaring the Global variable after we are using it in the “main” function.
Question 4: What will be the output of the below program?
#include <stdio.h> int number = 10; number = 20; int main() { printf("%d", number); return 0; }
Output: re-definition error. This is because the Re-definition of Global variables is not allowed in the C language. In the above example, we are trying to redefine the Global variable with number= 20.
Question 5: What will be the output of the below program?
#include <stdio.h> int number1 = 10; int number2 = number1 ; int main() { printf("%d", number1); return 0; }
Output: Compilation Error. We cannot directly assign one “Global variable” to another “Global variable” outside the function. In the above example, we are trying to assign the Global variable number1 to another Global variable number2.
In the next article, I am going to discuss Functions in C Language. Here, in this article, I try to explain the Types of Variables in C Language with examples, and I hope you enjoy this type of Variables in C Language with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about these Types of Variables in the C Language article.