Home > Software engineering >  initialize array of structs with const
initialize array of structs with const

Time:04-05

typedef struct{     
  int nim;         
  float ipk;         
  char nama[50];         
  char alamat[50];     
} dataMahasiswa;

int main() {    
    dataMahasiswa p[MAX];
    
    p[0] = (const dataMahasiswa){120321004,4.00,"DAVID LEO","SURABAYA"};
    p[1] = (const dataMahasiswa){120321002,4.00,"HANIF AHSANI","NGANJUK"};
}

what is the meaning and function of const dataMahasiswa?

when I remove the (const dataMahasiswa) what happens is (error: expected expression before '{' token)

CodePudding user response:

The qualifier const is redundant in the compound literals

p[0] = (const dataMahasiswa){120321004,4.00,"DAVID LEO","SURABAYA"};
p[1] = (const dataMahasiswa){120321002,4.00,"HANIF AHSANI","NGANJUK"};

You could just write

p[0] = (dataMahasiswa){120321004,4.00,"DAVID LEO","SURABAYA"};
p[1] = (dataMahasiswa){120321002,4.00,"HANIF AHSANI","NGANJUK"};

In this two statements compound literals are assigned to two elements of the array p.

CodePudding user response:

This error occurred because the compiler couldn't get the right struct (data type) to convert the given data. This feature was first introduced in C99 you should must read this.

But, in C you don't need to type the struct name before {, most of the modern C compilers automatically does that.

Also, you don't need to write const before your struct name.

p[0] = (dataMahasiswa){120321004,4.00,"DAVID LEO","SURABAYA"};
p[1] = (dataMahasiswa){120321002,4.00,"HANIF AHSANI","NGANJUK"};
  • Related