Home »
C programming language
C FAQ - Can we initialize structure members within structure definition?
C programming FAQ: Can we initialize structure members within structure definition? Here, we will also learn how we can initialize the members of structure?
Submitted by IncludeHelp, on May 18, 2018
Que: Can we initialize structure members within structure definition?
No!
We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).
struct numbers{
int a=10;
int b=20;
};
Here, we are initializing a with 10 and b with 20 that will not be executed by the compiler and compiler will return an error.
Let’s see the example and error returns by the compiler
#include <stdio.h>
struct numbers{
int a=10;
int b=20;
};
int main()
{
//structure variable declaration
struct numbers num;
//printing the structure members
printf("a=%d, b=%d\n",num.a, num.b);
return 0;
}
Output
prog.c:4:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
int a=10;
^
prog.c: In function ‘main’:
prog.c:14:27: error: ‘struct numbers’ has no member named ‘a’
printf("a=%d, b=%d\n",num.a, num.b);
^
prog.c:14:34: error: ‘struct numbers’ has no member named ‘b’
printf("a=%d, b=%d\n",num.a, num.b);
^
prog.c:11:17: warning: variable ‘num’ set but not used [-Wunused-but-set-variable]
struct numbers num;
^~~
How to initialize structure members?
While declaring structure’s variable (object to the structure), we can assign the values of the members.
Syntax:
struct structure_name structure_variable_name ={value1, value2};
Example:
struct numbers num ={10,20};
Correct program:
#include <stdio.h>
struct numbers{
int a;
int b;
};
int main()
{
//structure variable declaration
struct numbers num ={10,20};
//printing the structure members
printf("a=%d, b=%d\n",num.a, num.b);
return 0;
}
Output
a=10, b=20