Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use constants as statements in C?

Tags:

c

Why does this program below not show any error ?

int main (void) {     "ANGUS";     1;     3.14;     return 0; } 
like image 564
Angus Avatar asked Aug 24 '11 08:08

Angus


People also ask

Can C functions be constant?

Not in standard C, since there are no classes or objects (as in "class instances, i.e. collections of data with associated functions"), there's nothing for the function to be const "against".

How do you declare constants in C?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

Why would you use a constant instead of a variable?

Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.

Why should you not use #define to declare a constant?

The disadvantage of #define is that is replaces every occurence of the name, while const variables get normal lookup, so you have less risk of naming conflicts and it's not typesafe. The advantage of #define is that it guarantees constness and therefore there will be no backing variable.


1 Answers

Each of those statements are expressions that evaluate to a value, which is then discarded. Compare it to if you called a function that returned an int, a char or a float, without using the return value. That's also an expression that evaluates to a value.

It is not uncommon to have functions that return values that the caller may or may not be interested in, like for example where printf("%d", 9001) returns the number of characters printed. A caller can use the number returned, or they can just ignore it.

If the compiler complained whenever you ignored a return value, you'd have a very noisy build log. Some compilers however diagnose (if sufficient warning flags are enabled) such pointless side-effect-less uses of literals and variables.

like image 77
Lars Viklund Avatar answered Sep 25 '22 09:09

Lars Viklund