2

I have the following typedef struct

typedef unsigned int NOTE_FREQ;
/*******A_MUSIC_ELEMENT structure****************/ 
typedef struct { 
    NOTE_FREQ frequencyValue; 
    int duration; 
} A_MUSIC_ELEMENT; 

Now I want to make an array of A_MUSIC_ELEMENT and with specific values.

A_MUSIC_ELEMENT ZTitleScreen[] = {{60, 20},{80, 50}}; 

and it compiles fine. but to make things more readable I try to set

int BPM1 = 60;
int BPM2 = 80;
int TIME1 = 20;
int TIME2 = 50;
A_MUSIC_ELEMENT ZTitleScreen[] = {{BPM1, TIME1},{BPM2, TIME2}}; 

and i get an error saying :

constant expression required 

i don't know why since it should be the same thing. i am using windows 8, mplab x IDE, hi tech c compiler. any help to demystify this thanks.

2 Answers 2

4

The value of BPM1 could change so the compiler won't allow it as an argument for the initializer list.

If you want to use named constants, try using enum.

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

1 Comment

In c++11 you have a features called const_exp, but in C you may be stuck with doing HALF_NOTE as a macro.
1

6.7.9 Initialization

     4. All the expressions in an initializer for an object that has static or 
thread storage duration shall be constant expressions or string literals.

Below are the different ways in which you can initialize a structure...

struct date date1= { 9, 5, 1982};           // Initializing structure
struct date date2 = { .day = 9, .month = 5};// Designated initializer
struct date date3 = {0};                    // Initializing all members to 0
struct date date4;
struct date date5 = date1;                  // Initialization using variable

date4.day = 9;      // Member wise initialization
date4.month = 5;    // Member wise initialization
date4.year = 1982;  // Member wise initialization

2 Comments

thanks. where is this from? I only understand the main idea from this. all this static and thread storage stuff I would have to research to understand it
The above statement is from C standard (ISO/IEC 9899:201x). Below code I typed it.

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.