Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "Syntax of Expression"

Tags:

c

I am reading The C Programming Language written by K&R and I am stuck on a statement which says something about declarations:

The syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear.

enter image description here

This is what I have understood from the above statement:

When we declare a variable (e.g. int a), it means that when that identifier (a) is used in an expression, it will return a value of the specified type (int).

Am I correct? And what is actually meant by syntax of expression?

like image 624
Bhaskar Avatar asked Jan 28 '23 18:01

Bhaskar


1 Answers

Let's look at a few examples.

With

int *A;

you can use *A in an expression and it will have type int, so A must be a pointer to int.

With

int A[100];

you can use A[i] in an expression and it will have type int, so A must be an array of int.

But you can construct more complex declarations:

With

int (((A)));

you can use (((A))) in an expression and it will have type int, so A must be an int.

With

int *A[100];

you can use *A[i] in an expression and it will have type int, so A ...

  • must be an array ...
  • and its elements must be pointers to int

so A must be an array of pointers to int.

Similarly, with

int (*A)[100];

you can use (*A)[i] in an expression and it will have type int, so A ...

  • must be a pointer ...
  • and the thing it's pointing to must be an array of int

so A must be a pointer to an array of int.


This is what is meant by "the syntax of the declaration for a variable mimics the syntax of expressions": When you declare a variable, you write a sort of mini-expression whose result type is given, and by reasoning backwards, you can deduce the type of the variable being declared.

like image 180
melpomene Avatar answered Feb 04 '23 07:02

melpomene