Search This Blog

About Me

My photo
Hello, my name is Gurnoor Singh. I am the creator of NoorEDU, a blog for about education . I live in India. I study in BCA Trade.In my free time, I enjoy hiking, practicing photography, and exploring the city by bike.

Wednesday, 23 September 2020

Static in C

 

Static in C

Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.

Static keyword can be used in the following situations:

  • Static global variable
    When a global variable is declared with a static keyword, then it is known as a static global variable. It is declared at the top of the program, and its visibility is throughout the program.
  • Static function
    When a function is declared with a static keyword known as a static function. Its lifetime is throughout the program.
  • Static local variable
    When a local variable is declared with a static keyword, then it is known as a static local variable. The memory of a static local variable is valid throughout the program, but the scope of visibility of a variable is the same as the automatic local variables. However, when the function modifies the static local variable during the first function call, then this modified value will be available for the next function call also.
  • Static member variables
    When the member variables are declared with a static keyword in a class, then it is known as static member variables. They can be accessed by all the instances of a class, not with a specific instance.
  • Static method
    The member function of a class declared with a static keyword is known as a static method. It is accessible by all the instances of a class, not with a specific instance.

Let's understand through an example.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.  printf("%d",func());  
  5. printf("\n%d",func());  
  6.  return 0;  
  7. }  
  8. int func()  
  9. {   
  10.     int count=0; // variable initialization  
  11.     count++; // incrementing counter variable  
  12.   
  13.    return count; }  

In the above code, the func() function is called. In func(), count variable gets updated. As soon as the function completes its execution, the memory of the count variable will be removed. If we do not want to remove the count from memory, then we need to use the count variable as static. If we declare the variable as static, then the variable will not be removed from the memory even when the function completes its execution.

Output

1                                                                                                                               
1

Static variable

A static variable is a variable that persists its value across the various function calls.

Syntax

The syntax of a static variable is given below:

  1. static data_type variable_name;   

Let's look at a simple example of static variable.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.    printf("%d",func());  
  5.    printf("\n%d",func());  
  6.   
  7.     return 0;  
  8. }  
  9. int func()  
  10. {  
  11.     static int count=0;  
  12.     count++;  
  13.     return count;  
  14. }  

In the above code, we have declared the count variable as static. When the func() is called, the value of count gets updated to 1, and during the next function call, the value of the count variable becomes 2. Therefore, we can say that the value of the static variable persists within the function call.

Output

1                                                                                                                             
2        

Static Function

As we know that non-static functions are global by default means that the function can be accessed outside the file also, but if we declare the function as static, then it limits the function scope. The static function can be accessed within a file only.

The static function would look like as:

  1. static void func()  
  2. {  
  3.     printf("Hello javaTpoint");  
  4. }  

Differences b/w static and global variable

Global variables are the variables that are declared outside the function. These global variables exist at the beginning of the program, and its scope remains till the end of the program. It can be accessed outside the program also.

Static variables are limited to the source file in which they are defined, i.e., they are not accessible by the other source files.

Both the static and global variables have static initialization. Here, static initialization means if we do not assign any value to the variable then by default, 0 value will be assigned to the variable.

Differences b/w static local and static global variable

Static global variable

If the variable declared with a static keyword outside the function, then it is known as a static global variable. It is accessible throughout the program.

Static local variable

The variable with a static keyword is declared inside a function is known as a static local variable. The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution. When the function modifies the value of the static local variable during one function call, then it will remain the same even during the next function call.

Properties of a static variable

The following are the properties of a static variable:

  • The memory of a static variable is allocated within a static variable.
  • Its memory is available throughout the program, but the scope will remain the same as the automatic local variables. Its
  • value will persist across the various function calls.
  • If we do not assign any value to the variable, then the default value will be 0.
  • A global static variable cannot be accessed outside the program, while a global variable can be accessed by other source files.

Tokens in C

 

Tokens in C

Tokens in C is the most important element to be used in creating a program in C. We can define the token as the smallest individual element in C. For `example, we cannot create a sentence without using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can say that tokens in C is the building block or the basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

  • Keywords in C
  • Identifiers in C
  • Strings in C
  • Operators in C
  • Constant in C
  • Special Characters in C

Let's understand each token one by one.

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they cannot be used as the variable names. If the keywords are used as the variable names, it means that we are assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given below:

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofvolatile
doifstaticwhile

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C are given below:

  • The first character of an identifier should be either an alphabet or an underscore, and then it can be followed by any of the character, digit, or underscore.
  • It should not begin with any numerical digit.
  • In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive.
  • Commas or blank spaces cannot be specified within an identifier.
  • Keywords cannot be represented as an identifier.
  • The length of the identifiers should not be more than 31 characters.
  • Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the end of the string. This null character denotes the end of the string. Strings in C are enclosed within double quotes, while characters are enclosed within single characters. The size of a string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which the operators are applied are known as operands. Operators are applied between the operands. Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list of the binary operators:

  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Conditional Operators
  • Assignment Operator
  • Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

  • Using const keyword
  • Using #define pre-processor

Types of constants in C

ConstantExample
Integer constant10, 11, 34, etc.
Floating-point constant45.6, 67.8, 11.2, etc.
Octal constant011, 088, 022, etc.
Hexadecimal constant0x1a, 0x4b, 0x6b, etc.
Character constant'a', 'b', 'c', etc.
String constant"java", "c++", ".net", etc.

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used for another purpose.

  • Square brackets [ ]: The opening and closing brackets represent the single and multidimensional subscripts.
  • Simple brackets ( ): It is used in function declaration and function calling. For example, printf() is a pre-defined function.
  • Curly braces { }: It is used in the opening and closing of the code. It is used in the opening and closing of the loops.
  • Comma (,): It is used for separating for more than one statement and for example, separating function parameters in a function call, separating the variable when printing the value of more than one variable using a single printf statement.
  • Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we are using the header file.
  • Asterisk (*): This symbol is used to represent pointers and also used as an operator for multiplication.
  • Tilde (~): It is used as a destructor to free memory.
  • Period (.): It is used to access a member of a structure or a union.

Constants and What are literals?

 

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C

ConstantExample
Decimal Constant10, 20, 450 etc.
Real or Floating-point Constant10.3, 20.2, 450.6 etc.
Octal Constant021, 033, 046 etc.
Hexadecimal Constant0x2a, 0x7b, 0xaa etc.
Character Constant'a', 'b', 'x' etc.
String Constant"c", "c program", "c in javatpoint" etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

  1. const keyword
  2. #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.

  1. const float PI=3.14;  

Now, the value of PI variable can't be changed.

  1. #include<stdio.h>    
  2. int main(){    
  3.     const float PI=3.14;    
  4.     printf("The value of PI is: %f",PI);    
  5.     return 0;  
  6. }     

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

  1. #include<stdio.h>    
  2. int main(){    
  3. const float PI=3.14;     
  4. PI=4.5;    
  5. printf("The value of PI is: %f",PI);    
  6.     return 0;  
  7. }     

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive later.




What are literals?

Literals are the constant values assigned to the constant variables. We can say that the literals represent the fixed values that cannot be modified. It also contains memory but does not have references as variables. For example, const int =10; is a constant integer expression in which 10 is an integer literal.

Types of literals

There are four types of literals that exist in C programming:

  • Integer literal
  • Float literal
  • Character literal
  • String literal

Integer literal

It is a numeric literal that represents only integer type values. It represents the value neither in fractional nor exponential part.

It can be specified in the following three ways:

Decimal number (base 10)

It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.

Octal number (base 8)

It is defined as a number in which 0 is followed by digits such as 0,1,2,3,4,5,6,7. For example, 012, 034, 055, etc.

Hexadecimal number (base 16)

It is defined as a number in which 0x or 0X is followed by the hexadecimal digits (i.e., digits from 0 to 9, alphabetical characters from (a-z) or (A-Z)).

An integer literal is suffixed by following two sign qualifiers:

L or l: It is a size qualifier that specifies the size of the integer type as long.

U or u: It is a sign qualifier that represents the type of the integer as unsigned. An unsigned qualifier contains only positive values.

Note: The order of the qualifier is not considered, i.e., both lu and ul are the same.

Let's look at a simple example of integer literal.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     const int a=23;  // constant integer literal  
  5.     printf("Integer literal : %d", a);  
  6.     return 0;  
  7. }  

Output

Integer literal : 23

Float literal

It is a literal that contains only floating-point values or real numbers. These real numbers contain the number of parts such as integer part, real part, exponential part, and fractional part. The floating-point literal must be specified either in decimal or in exponential form. Let's understand these forms in brief.

Decimal form

The decimal form must contain either decimal point, exponential part, or both. If it does not contain either of these, then the compiler will throw an error. The decimal notation can be prefixed either by '+' or '-' symbol that specifies the positive and negative numbers.

Examples of float literal in decimal form are:

  1. 1.2, +9.0, -4.5  

Let's see a simple example of float literal in decimal form.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     const float a=4.5; // constant float literal  
  5.     const float b=5.6; // constant float literal  
  6.     float sum;  
  7.     sum=a+b;  
  8.     printf("%f", sum);  
  9.     return 0;  
  10. }  

Output

10.100000

Exponential form

The exponential form is useful when we want to represent the number, which is having a big magnitude. It contains two parts, i.e., mantissa and exponent. For example, the number is 2340000000000, and it can be expressed as 2.34e12 in an exponential form.

Syntax of float literal in exponential form

  1. [+/-] <Mantissa> <e/E> [+/-] <Exponent>  

Examples of real literal in exponential notation are:

  1. +1e23, -9e2, +2e-25  

Rules for creating an exponential notation

The following are the rules for creating a float literal in exponential notation:

  • In exponential notation, the mantissa can be specified either in decimal or fractional form.
  • An exponent can be written in both uppercase and lowercase, i.e., e and E.
  • We can use both the signs, i.e., positive and negative, before the mantissa and exponent.
  • Spaces are not allowed

Character literal

A character literal contains a single character enclosed within single quotes. If multiple characters are assigned to the variable, then we need to create a character array. If we try to store more than one character in a variable, then the warning of a multi-character character constant will be generated. Let's observe this scenario through an example.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     const char c='ak';  
  5.     printf("%c",c);  
  6.     return 0;  
  7. }  

In the above code, we have used two characters, i.e., 'ak', within single quotes. So, this statement will generate a warning as shown below.

Warning generated:

  1. main.c:6:18: warning: multi-character character constant  
  2.       [-Wmultichar]  
  3.     const char c='ak';  
  4. main.c:6:18: warning: implicit conversion from 'int' to 'char'  
  5.       changes value from 24939 to 107 [-Wconstant-conversion]  
  6.     const char c='ak';  
  7.                ~ ^~~~  
  8. 2 warnings generated.  
  9. ? ./main  

Representation of character literal

A character literal can be represented in the following ways:

  • It can be represented by specifying a single character within single quotes. For example, 'a', 'b', etc.
  • We can specify the escape sequence character within single quotes to represent a character literal. For example, '\n', '\a', '\b'.
  • We can also use the ASCII in integer to represent a character literal. For example, the ascii value of 65 is 'A'.
  • The octal and hexadecimal notation can be used as an escape sequence to represent a character literal. For example, '\023', '\0x12'.

String literal

A string literal represents multiple characters enclosed within double-quotes. It contains an additional character, i.e., '\0' (null character), which gets automatically inserted. This null character specifies the termination of the string. We can use the '+' symbol to concatenate two strings.

For example,

String1= "javatpoint";

String2= "family";

To concatenate the above two strings, we use '+' operator, as shown in the below statement:

"javatpoint " + "family"= javatpoint family


Bitwise Operator in C