I wrote this simple code in devc++. On compiling, the computer is showing syntax error at line int P = rand(); ... while the same line, if I write in the main function gets compiled easily. Please tell me what's going on!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct poclick
{
      int P = rand();
};
int main ()
{
    int num = 4; // number of cases
    int nj;
}

That is because structures and functions are completely different.

Structures are blocks of data that are made up of primitive data types (int, char, float) or other structures and you cannot set default values to them within the structure. However you can make a function to set the values or directly modify them.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct
{
	int P;
}poclick;

void poclickInit(poclick *in)
{
	in->P = rand();
}

int main()
{
	poclick A;

	A.P = 0; //directly modifying the value
	printf("%d\n", A.P);

	poclickInit(&A); //using function to modify the value
	printf("%d\n", A.P);

	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.