Continue to Site

Welcome to

Welcome to our site! is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Basic C question about multiplication of int and char variables

Not open for further replies.

Jos Brink

Member level 3
Jan 28, 2004
Reaction score
Trophy points
Activity points
Ok, I had a bug in my software. have a look at this little code:

unsigned char i, j, *ptr1,*ptr2, temp, x_max, y_max;
unsigned char row_index;
unsigned int row_offset,bitmap_offset;

row_offset = x_max * row_index;

in this case x_max = 122, and row_index varies from 0 to 3.

during this multiply, row_offset got wrong values. By changing row_index to an unsigned int, the problem was over.

Can someone explain why row_index has to be an int instead of a char, and x_max not?


btw: I'm using codevision

Added after 20 minutes:

ok, i wrote a little test program to find out what's happening.

unsigned int k, z;
unsigned char i , j ,x, y;

x = 122;
i = 122;

for (y = 0;y < 8; y++)
z = x * y;
putchar( z >> 8 );
putchar( z & 0x00FF);

// output was: 0000, 007A, 00F4, 006E, 00E8, 0062, 00DC, 0056

z = 122;

for (j = 0;j < 8; j++)
k = z * j;
putchar( k >> 8 );
putchar( k & 0x00FF);

// output was: 0000, 007A, 00F4, 016E, 01E8, 0262, 02DC, 0356

It seems that one of the two variables needs to be an int, it doesn't matter wich one.
Does the compiler use the variables also for temporary storage?

Re: Basic C question.

int = uchar * uchar;
when compiler sees this *, it does multiplication & the result is of type uchar (8bits value) & I think 3*122 needs more than 8bits storage. what the compiler will do in this case it will truncate the most significant bits & keep only the 8least ones.
For assignment , It find LHS is unsigned int so it will expand the uchar to uint by zeros. Thats why the result differed.
To over come you should cast one of the multiplication operands to the result type in order to promote the other opernad to the result type & keeps the truncated data before.

Basic C question.

Sounds like your compiler is not ANSI C compliant. It should automatically promote your two unsigned char values to int before it multiplies them.

The CodeVisionAVR 1.24.7 user manual describes a compiler setting "promote char to int" for ANSI compatibility. Try it.

Not open for further replies.

Part and Inventory Search

Welcome to