andi_dvga
andi_dvga

Reputation: 13

initialize array of structs with const

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)

Upvotes: 1

Views: 92

Answers (2)

Darth-CodeX
Darth-CodeX

Reputation: 2437

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

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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.

Upvotes: 2

Related Questions