Conditional and assignment operator in expression

In this example we will be learning how to use conditional and assignment operator in single expression. In previous chapters we have learnt indirect use of if statement in expression

Use of conditional and assignment operator in expression

Consider below example where we have used the conditional and assignment operator in an expression.

#include <stdio.h>
int main(int argc, char *argv[]) {
   int a = 40, b = 30, c;
   c = !a <= !(c = b);
   printf("%d", c);
   return 0;
}

Output :

1

Explanation

Below is the explanation of the complex expression containing conditional and assignment operators -

conditional and assignment operator in expression

Step 1 : Solve the bracket first

While solving an expression, it is thumb rule to solve the bracket first. Lets see how we are solving the brackets -

c = !a <= !(c = b);
c = !a <= !(Assign Value of b to c);
c = !a <= !(30);

so at the end of step 1 our expression will be modified into following expression

c = !a <= !30;

We have replaced the expression (c=b) with 30 in original expression

Step 2 : List our operators with precedence

Now we need to arrange all the operators in the decreasing order of precedence. We are having 2 unary operators, 1 assignment and 1 conditional operator

Re-commanded Article : Operator Precedence and Priority

After listing out all the operators in descending order of priority -

NoOperator NamePriority
1Unary Not OperatorPriority 1
2Unary Not OperatorPriority 2
3Less than or equal toPriority 3
4Assignment OperatorPriority 4

"Not" Operator has higher priority than <= Operator. so we can write it as -

c = !a= !40 = 0

Replace !a by "0" as we calculated it in the above expression statement.

c = 0<=!30

Step 3 : Solve expression recursively

Now again we find there are 3 operators i.e equal to, greater than equal to and Not operator.

"Not" Operator has Higher Priority than any other priority specified in the expression

!30 = 0

so after replacing the expression will be like this -

c = 0 <= 0

Now when we try to solve then we find less than or equal to operator will get higher priority and obviously 0 <= 0 is True condition so it returns 1

c = 1

Relational operators in an expression : C Programming

In this tutorial we are going to see how we can use relational operators in an expression.

Relational operators in an expression

First of all we are going to list out the different relational operators.


Operator,Name of Operator
>,Greater Than
<,Less Than >=,Greater than Operator
<=,Less than Operator ==,Comparison Operator !=,Not equal to Operator [/table]

Use of relational operators in an expression is nothing but using if statement in an expression indirectly

Reading expression containing relational operators

If we use any of the operator listed in above table in your expression then that part of expression will provide you either 0 or 1 as a result. Consider below example -

res = 100 > 20

above expression will assign value 1 to a variable res because relational operators in an expression is used. Consider below example -

Thumb rules for solving expression

Keep in mind simple 2 thumb rules when you find relational operators in an expression -

  1. Check whether the expression is true or false. If expression is true then simply replace the expression with 1
  2. If expression results into false statement then replace the expression with 0

Examples

Example #1 : Usage of relational operator

#include <stdio.h>
int main(int argc, char *argv[]) {
   int num1 = 100;
   int num2 = 100;
   printf("%d",num1 >  num2);
   printf("%d",num1 >= num2);
   printf("%d",num1 <= num2);
   printf("%d",num1 <  num2);
   return 0;
}

Output :

0 1 1 0

You can see, we have used the relational operators inside the expression and it returns the result with values either 0 or 1. Operation is similar to below statement -

if(num1 > num2)
   printf("1");
else
   printf("0");

Example #2 : Indirect use of if statement

#include<stdio.h>
void main()
{
  int num1 = 100,num2=200,num3;
  num3 = ( num1 >= 100 ) + (num2 < 50 );
  printf("%d",num3);
}

Output :

1

Explanation :

Consider this statement -

num3 = ( num1 >= 100 );

above statement can be written in following way -

if( num1 >= 100 )    
   num3 = 1;
else    
   num3 = 0;

considering above thumb rules we can calculate the value of num3 as -

num3 = ( num1 >= 100 ) + (num2 < 50 );
num3 = 1 + (num2 < 50 );  // ( num1 >= 100 ) is True
num3 = 1 + 0;             // ( num2 <  50  ) is False
num3 = 1;

C accessing union members

We have already seen tutorial which provides the basics of union in c programming. In this tutorial we are learning the way for accessing union members in C Programming.

C Programming Accessing union members

While accessing union, we can have access to single data member at a time. we can access single union member using following two Operators -

  1. Using DOT Operator
  2. Using ARROW Operator

Accessing union members DOT operator

In order to access the member of the union we are using the dot operator. DOT operator is used inside printf and scanf statement to get/set value from/of union member location.

Syntax :

variable_name.member

consider the below union, when we declare a variable of union type then we will be accessing union members using dot operator.

union emp
{
int id;
char name[20];
}e1;

id can be Accessed by - union_variable.member

SyntaxExplanation
e1.idAccess id field of union
e1.nameAccess name field of union

Accessing union members Arrow operator

Instead of maintaing the union variable suppose we store union at particular address then we can access the members of the union using pointer to the union and arrow operator.

union emp
{
int id;
char name[20];
}*e1;

id can be Accessed by - union_variable->member

SyntaxExplanation
e1->idAccess id field of union
e1->nameAccess name field of union

C Programs

Program #1 : Using dot operator

#include <stdio.h>
union emp
{
  int id;
  char name[20];
}e1;
int main(int argc, char *argv[])
{
    e1.id = 10;
    printf("\nID   : %d",e1.id);
    strcpy(e1.name,"Pritesh");
    printf("\nName : %s",e1.name);
    return 0;
}

Output :

ID   : 10
Name : Pritesh

Program #2 : Accessing same memory

#include <stdio.h>
union emp
{
  int id;
  char name[20];
}e1;
int main(int argc, char *argv[])
{
    e1.id = 10;
    strcpy(e1.name,"Pritesh");
    printf("\nID   : %d",e1.id);
    printf("\nName : %s",e1.name);
    return 0;
}

Output :

ID   : 1953067600
Name : Pritesh

As we already discussed in the previous article of union basics, we have seen how memory is shared by all union fields. In the above example -

Total memory for union = max(sizeof(id),sizeof(name)) 
                       = sizeof(name)
                       = 20 bytes 

Firstly we have utilized first two bytes out of 20 bytes for storing integer value. After execution of statement again same memory is overridden by character array so while printing the ID value, garbage value gets printed

Program #3 : Using arrow operator

#include <stdio.h>
union emp
{
  int id;
  char name[20];
}*e1;
int main(int argc, char *argv[])
{
    e1->id = 10;
    printf("\nID   : %d",e1->id);
    strcpy(e1->name,"Pritesh");
    printf("\nName : %s",e1->name);
    return 0;
}

Output :

ID   : 10
Name : Pritesh

C pointer to union

Previously we have learnt about basics of union in c programming and way to access a member of union.

In this tutorial we will be learning about pointer to union i.e pointer which is capable of storing the address of an union in c programming.

C programming pointer to union

We know that pointer is special kind of variable which is capable of storing the address of a variable in c programming.

Pointer to union : Pointer which stores address of union is called as pointer to union

Syntax

union team t1;    //Declaring union variable
union team *sptr; //Declaring union pointer variable 
sptr = &t1;       //Assigning address to union pointer

In the above syntax that we have shown -

  1. Step 1 : We have declared a variable of type union.
  2. Step 2 : Now declare a pointer to union
  3. Step 3 : Uninitialized pointer is of no use so need to initialize it

Recommended Article : See some common mistakes of a pointer

Program

#include<stdio.h>
union team {
  char *name;
  int members;
  char captain[20];
};
int main()
{
union team t1,*sptr = &t1;
t1.name = "India";
printf("\nTeam : %s",(*sptr).name);
printf("\nTeam : %s",sptr->name);
return 0;
}

Output :

Team = India
Team = India

Program explanation

  1. sptr is pointer to union address.
  2. -> and (*). both represents the same.
  3. These operators are used to access data member of structure by using union’s pointer.

Summary

In order to access the members of union using pointer we can use following syntax -

CodeExplanation
(*sptr).nameUsed for accessing name
sptr->nameUsed for accessing name

R-Value of Expression : C Programming

In the previous chapter we have learnt about the Lvalue of an expression in this chapter we are going to learn R-Value of Expression.

What is R-Value of Expression ?

  1. R Value stands for Right value of the expression.
  2. In any Assignment statement R-Value of Expression must be anything which is capable of returning Constant Expression or Constant Value.
  3. R Value Can be anything of following -
Examples of R-Value of Expression
VariableConstant
FunctionMacro
Enum ConstantAny other data type

Diagram Showing Lvalue :

Example of R-Value of Expression

#include<stdio.h>
int main()
{
int num;
num = 5;
return(0);
}

In the above example, Constant Value 5 is assigned to the variable will be considered as right Value of the variable.

Tips : R-Value of Expression

Tip 1 : R value may be constant or constant expression

num = 20;      //Constant RValue
num = 20 + 20; //Constant Expression as RValue
  1. In the example, we have assigned constant value to the variable.
  2. Constant value “20” is considered as RValue.
  3. In the next line we have assigned constant expression to the variable. “20 + 20” will be evaluated first and then result of expression will be assigned to an Variable.

Tip 2 : R value may be MACRO

#define MAX 20
main() {
   int num = MAX;
}

If we have defined a MACRO then we can use MACRO as right value. In the above example we have assigned the 20 to the variable “num”.

In case if we defined the MACRO value of different data type then it may results into compile error.

Tip 3 : R Value may be variable

#define MAX 20
main() 
{
   int flag = 0;
   int num  = flag;
}

For more information , Visit MSDN library.

C union declaration

How to Declare Union in C ?

  1. Union is similar to that of Structure. Syntax of both are same but major difference between structure and union is ‘memory storage‘.
  2. In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types,
  3. Union can handle only one member at a time.

Syntax :

union tag
{
   union_member1;
   union_member2;
   union_member3;
   ..
   ..
   ..
   union_memberN;
}instance;

Note :

Unions are Declared in the same way as a Structure.Only “struct Keyword” is replaced with union

Sample Declaration of Union :

union stud 
{
   int roll;
   char name[4];
   int marks;
}s1;<

How Memory is Allocated ?

So From the Above fig. We can Conclude -

  1. Union Members that compose a union, all share the same storage area within the computers memory
  2. Each member within a structure is assigned its own unique storage area
  3. Thus unions are used to observe memory.
  4. Unions are useful for application involving multiple members , where values need not be assigned to all the members at any one time.

L-Value of Expression : C Programming

In the previous chapter we have learnt about C Programming Expressions, in this chapter we will be learning about L-Value of Expression.

What is L-Value of Expression ?

  1. L-Value stands for left value
  2. L-Value of Expressions refer to a memory locations
  3. In any assignment statement L-Value of Expression must be a container(i.e. must have ability to hold the data)
  4. Variable is the only container in C programming thus L Value must be any Variable.
  5. L Value Cannot be Constant,Function or any of the available data type in C

Diagram Showing L-Value of Expression :

Example of L-Value of Expression :

#include<stdio.h>
int main()
{
  int num;
  num = 5;
return(0);
}

In the above expression, Constant value 5 is being assigned to a variable ‘num’. Variable ‘num’ is called as storage region’s , ‘num’ can considered as LValue of an expression.

Re-commanded Concepts : Concept of Variables and Constants in C

Important Tips :

Below are some of the tips which are useful to make your concept about L-Value of Expression more clear.

Lvalue cannot be a Constant

int main()
{
int num;
5 = num;  //Error
return(0);
}

You cannot assign the value or any constant value to another constant value because meaning of constant is already defined and it cannot be modified.

Lvalue cannot be a Constant Variable

Even we cannot assign a value to a constant variable. Constant variable should not be used as L Value.

int main()
{
const num;
num = 20;  //Error
return(0);
}

Lvalue cannot be a MACRO

We know that macros gets expanded before processing source code by compiler. All the macros will be replaced by defined value using pre-processor before compiling program.

#define MAX 20
int main()
{
MAX = 20;  //Error
return(0);
}

pre-processor will replace all the occurances of macros and hand over modified source code to compiler. following code will be given to compiler after doing pre-processor task

#define MAX 20
int main()
{
20 = 20;
return(0);
}

Re-commanded Reading : Preprocessor macro

Lvalue cannot be a Enum Constant

enum {JAN,FEB,MARCH};
int main()
{
JAN = 20;  //Error
return(0);
}

Lvalue cannot be a Data Type

#define<stdio.h>
#define max 125
struct book{
  char *name;
  int  pages;
};
void main()
{
book = {"C Programming",100};
}

L-Value Require error ?

Causes of Error :

  1. Whenever we are trying to assign value to constant value
  2. Whenever we are trying to increment or decrement Constant Expression
  3. Inside if statement , if we try to write comparison operator as “= =” instead of “==”, then we will get this error.

Solution :

Solution to this problem is very simple -

  1. Always try to assign constant value to “Variable“.
  2. If you are using comparison operator then we don’t provide space in between operators.

In the next chapter we will be learning RValue of an expression which is also called as right value of an expression.

C union basics

Union in C Programming :

In C Programming we have came across Structures. Unions are similar to structure syntactically.Syntax of both is almost similar. Let us discuss some important points one by one -

Note #1 : Union and Structure are Almost Similar

union stud 
{
   int roll;
   char name[4];
   int marks;
}s1;
struct stud 
{
   int roll;
   char name[4];
   int marks;
}s1;

If we look at the two examples then we can say that both structure and union are same except Keyword.

Note #2 : Multiple Members are Collected Together Under Same Name

int roll;
char name[4];
int marks;

We have collected three variables of different data type under same name together.

Note #3 : All Union Members Occupy Same Memory Area


For the union maximum memory allocated will be equal to the data member with maximum size. In the example character array ‘name’ have maximum size thus maximum memory of the union will be 4 Bytes.

Maximum Memory of Union = Maximum Memory of Union 
Data Member

Note #4 : Only one Member will be active at a time.

Suppose we are accessing one of the data member of union then we cannot access other data member since we can access single data member of union because each data member shares same memory. By Using Union we can Save Lot of Valuable Space

Simple Example :

union u
{
char a;
int b;
}

C Programming Expression

A. C Programming Expression :

  1. In programming, an expression is any legal combination of symbols that represents a value. [Definition from Webopedia]
  2. C Programming Provides its own rules of Expression, whether it is legal expression or illegal expression. For example, in the C language x+5 is a legal expression.
  3. Every expression consists of at least one operand and can have one or more operators.
  4. Operands are values and Operators are symbols that represent particular actions.

Valid C Programming Expression :

C Programming code gets compiled firstly before execution. In the different phases of compiler, c programming expression is checked for its validity.

ExpressionsValidity
a + bExpression is valid since it contain + operator which is binary operator
+ + a + bInvalid Expression

Priority and Expression :

In order to solve any expression we should have knowledge of C Programming Operators and their priorities.

Types of Expression :

In Programming, different verities of expressions are given to the compiler. Expressions can be classified on the basis of Position of Operators in an expression -

TypeExplanationExample
InfixExpression in which Operator is in between Operandsa + b
PrefixExpression in which Operator is written before Operands + a b
PostfixExpression in which Operator is written after Operandsa b +

These expressions are solved using the stack.

Examples of Expression :

Now we will be looking into some of the C Programming Expressions, Expression can be created by combining the operators and operands

Each of the expression results into the some resultant output value. Consider few expressions in below table

Expression Examples,Explanation
n1 + n2,This is an expression which is going to add two numbers and we can assign the result of addition to another variable.
x = y,This is an expression which assigns the value of right hand side operand to left side variable
v = u + a * t,We are multiplying two numbers and result is added to ‘u’ and total result is assigned to v
x <= y,This expression will return Boolean value because comparison operator will give us output either true or false ++j,This is expression having pre increment operator\, it is used to increment the value of j before using it in expression [/table]

Add numbers using function pointer

In this tutorial we will be learning how to add the two numbers using pointer in c programming.

Recommanded Articles : Function pointer | Function pointer reference

How to add two numbers using function pointer ?

#include<stdio.h>
 int sum (int n1,int n2);
 int main()
 {
 int num1 = 10;
 int num2 = 20;
 int result;
 int *(*ptr)(int,int);
 ptr = &sum;
 result = (*ptr)(num1,num2);
 printf("Addition : %d",result);
 return(0);
 }
int sum (int n1,int n2)
{
return(n1 + n2);
}

Output :

Addition : 20

Explanation :

  • Write whole program using normal function call i.e sum(num1,num2);
  • After you write whole code, just erase line in which we have called function and replace that line with following line -

Step 1 : Declaring Pointer Variable

int *(*ptr)(int,int);

means -

Declare pointer variable which is capable of storing address of function which have integer as return type and which takes 2 arguments

Step 2 : Initializing function Pointer

ptr = &sum;

using above statement we will be storing address of function in function pointer

Step 3 : Calling Function

result = (*ptr)(num1,num2);

It will call function sum(num1,num2). Above statement will be elaborated as -

result = (*ptr)(num1,num2);
result = (*&sum)(num1,num2);
result = (*&sum)(num1,num2);
result = (sum)(num1,num2);
result = sum(num1,num2);