1
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)

2
  • 1
    It's a C99 compound literal: en.cppreference.com/w/c/language/compound_literal Commented Apr 4, 2022 at 13:38
  • From a C point-of-view, p[0] = (const dataMahasiswa){120321004,4.00,"DAVID LEO","SURABAYA"}; is not initialization. It is assignment. Commented Apr 4, 2022 at 14:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

The question was not about C++, and I don't see any unnecessary "struct"
@aschepler That's just some extra points

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.