static

static keyword is used to declear static variable.

Syntax

static data_type var_name;

Declearation of static variable

static int score;

Properties of static variable:

  • local static variable visiblity will be within block. global decleared variable having global visiblity.
  • scope of an static variable will always whole program.
  • static variable gets memory at compile time
  • static can be used with all data types
  • default initial value of static variable are zero for integral data type and NULL for others
  • same ststic variable can be decleared many time but it should initilize only one time throught whole program.

Guess the output #1

#include <stdio.h>

static int foo;

int main()
{
	static int foo = 10;

	printf("foo: %d\n", foo);

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

foo: 10

Explanation: None.

Guess the output #2

#include <stdio.h>

static int foo = 10;

int main()
{
	static int foo;

	printf("foo: %d\n", foo);

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

foo: 0

Explanation: None.

Guess the output #3

#include <stdio.h>

static int foo = 10;

int main()
{
	static int foo = 20;

	printf("foo: %d\n", foo);

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

foo: 20

Explanation: None.

Guess the output #4

#include <stdio.h>

static int foo;
static int foo = 10;

int main()
{
	printf("foo: %d\n", foo);

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

foo: 10

Explanation: None.

Guess the output #5

#include <stdio.h>

static int foo = 20;
static int foo = 10;

int main()
{
	printf("foo: %d\n", foo);

	return 0;
}

Compiling this code produces following output. click on below icon to see the output.

static_5.c:4:12: error: redefinition of ‘foo’
    4 | static int foo = 10;
      |            ^~~
static_5.c:3:12: note: previous definition of ‘foo’ with type ‘int’
    3 | static int foo = 20;
      |            ^~~

Explanation: None.



©2023-2024 rculock.com