user806168
user806168

Reputation: 477

Using hex values in array index in C

I was reading through a C program which interfaces with hardware registers. The person has been using hexadecimal numbers as the index to an array such as :

app_base_add[0x30]  

I know that a[i] means *(a+i) which is *(a+(i*sizeof(typeof(a)))) so a hexadecimal index is probably a offset of the desired memory location in the address space w.r.t app_base_add.

Is this right?
And also given , say :

#define mm2s_start_add 0xc0000000;  

how would these assignments be different from each other in usage?

volatile unsigned int *app_base_add;  
app_base_add[0x30>>2]=0x1;    
app_base_add[0x30>>2]=1<<2;  
app_base_add[0x30>>2]=((unsigned int)mm2s_start_add);  //is this assignment valid??
app_base_add[0x30>>2]=((unsigned int *)mm2s_start_add);

Upvotes: 1

Views: 5461

Answers (3)

tomahh
tomahh

Reputation: 13661

At compile time, all values are treated them same way, even if they are written in hexadecimal, binary or decimal.

0x2a == 42 == b101010 == 052

The only assignement which could throw a warning is the cast to unsigned int, because your destination type is not an unsigned int

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25733

volatile unsigned int *app_base_add;
//app_base_add is a pointer to volatile memory(not initialized :()

app_base_add[0x30>>2]=0x1; // = app_base_add[12] = 1;

app_base_add[0x30>>2]=1<<2; // = app_base_add[12] = 4;

app_base_add[0x30>>2]=((unsigned int)mm2s_start_add); //is this assignment valid?? // yes its valid // = app_base_add[12] = 3221225472

app_base_add[0x30>>2]=((unsigned int *)mm2s_start_add); // = app_base_add[12] = interpret 3221225472 as an unsigned integer pointer and store it.

Upvotes: 0

AndersK
AndersK

Reputation: 36067

There is no difference writing 0x30 or 48 as index, it may just be easier to read for the programmer if say his documentation of the memory was written only with hex values but its just a matter of taste.

e.g.

app_base_add[0x30>>2]=0x1; 
is the same as writing app_base_add[12]=0x1; 
or even app_base_add[0x0C]=0x1; 

Upvotes: 2

Related Questions