int
, char
, float
, etc., followed by a variable name.#include <stdio.h>
// Global variable declaration
int global_var = 10;
void function() {
// Local variable declaration
int local_var = 20;
printf("Global Variable: %d\n", global_var);
printf("Local Variable: %d\n", local_var);
}
int main() {
// Accessing the global variable from main function
printf("Global Variable: %d\n", global_var);
function();
return 0;
}
In this example, when we run the program, it outputs:
Global Variable: 10
Global Variable: 10
Local Variable: 20
variable_name
(e.g., NameError)What causes it: A variable is not declared before being used in the current scope.
#include <stdio.h>
void function() {
int local_var = 20;
printf("Local Variable: %d\n", uninitialized_var); // Undefined variable error
}
Error message:
example.c: In function 'function':
example.c:7:3: warning: 'uninitialized_var' may be used uninitialized in this function [-Wmaybe-uninitialized]
printf("Local Variable: %d\n", uninitialized_var);
^~~~~~~~
Solution: Declare and initialize the variable before using it.
#include <stdio.h>
void function() {
int local_var = 20;
int uninitialized_var; // Initialize before use
printf("Local Variable: %d\n", local_var);
}
Why it happens: Compiler is not able to find the variable in the current scope when it's accessed.
How to prevent it: Always declare and initialize variables before using them.
What causes it: Trying to assign a value of one data type to a variable of another incompatible data type.
#include <stdio.h>
int main() {
char my_char = 'A';
float my_float = 3.14;
// Assigning a char value to a float variable
my_float = my_char; // TypeError
return 0;
}
Error message:
example.c:7:5: warning: assignment from incompatible pointer type [enabled by default]
my_float = my_char;
^~~~~~~~~~~~
Solution: Assign compatible data types to variables.
#include <stdio.h>
int main() {
char my_char = 'A';
float my_float = 3.14;
// Correctly assign a character code to an integer variable
int my_integer = (int)my_char;
return 0;
}
Why it happens: C does not implicitly convert data types, so explicit casting may be needed in certain cases.
How to prevent it: Always ensure that the data type being assigned is compatible with the target variable's data type.
Next steps: Study data structures like arrays and pointers, which further expand the possibilities of working with variables in C.