comp.lang.c
[Top] [All Lists]

assigment statement can use an expression when declaring a variable?

Subject: assigment statement can use an expression when declaring a variable?
From: vlsidesign
Date: Thu, 27 Mar 2008 14:32:17 -0700 PDT
Newsgroups: comp.lang.c

#include
int main(void)
{
float bread_price = 0.99;
int bread_count = 3;
float total_price = bread_count * bread_price; // this compiles okay

printf("total price is %.2f  \n", total_price);

return 0;
}

I am a newbie, and my understanding is that, roughly speaking, an
expression is usually a mix of operators and operands, and computes a
value. When you use an assigment operator during a declaration and
initialize, you can use an expression on the right hand side of the
assigment state? I do this above, and it compiles okay and seems to
work.

I believe you are only supposed to do this if the variables in the
expression have already had been assigned values. I changed the above
to not have them initialized and it still compiled, and then printed
out 0.00. Maybe the below is not legal C syntax, but I have a smart
compiler?

float bread_price;
int bread_count;
float total_price = bread_count * bread_price; // illegal but compiler
is smart??

Maybe this is not C legal since I never gave 'bread_price' or
'bread_count' a value, but I just have a good compiler that
automatically give them a 0.0 and 0 value respectively. I believe also
I am supposed to use the cast since I am mixing datatypes.

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy