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

Re: assigment statement can use an expression when declaring a variable

Subject: Re: assigment statement can use an expression when declaring a variable?
From:
Date: Thu, 27 Mar 2008 15:03:40 -0700 PDT
Newsgroups: comp.lang.c

On Mar 27, 11:32 pm, vlsidesign <ford...@xxxxxxxxx> wrote:
> #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
An expression is anything that can be evaluated. f() is an expression
and so is foo.
Quoting 1 from 6.5 in the C99 standard:
> An expression is a sequence of operators and operands that specifies 
> computation of a
> value, or that designates an object or a function, or that generates side 
> effects, or that
> performs a combination thereof.

> 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.
Yes. int n = 3, i = n; is valid.

> 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?
No, you were just lucky.
You cannot use uninitialized objects in C. It's not valid. (strictly
speaking, it invokes undefined behavior, refer to the standard for
more information)

> float bread_price;
> int bread_count;
> float total_price = bread_count * bread_price; // illegal but compiler
> is smart??
Notice something here:
If the object resides in the global namespace or the static qualifier
is present, the object will be initialized to 0 (or NULL or if it's an
aggregate, every member/element to 0 recursively)
so
#include <stdio.h>
int a;
int main(void) { static int b; printf("(a+b)*2 = %d\n", (a+b)*2);
return 0; }
is fine for every conforming implementation and the results are
predictable.

> 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.
No, there is no need for that. I do not remember the formal term for
this, but int is promoted to double, (bread_price too).

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