0

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;
}
2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by coder_naive
0

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;
}

Edited by sfuo: typo

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.