- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
function assign to variable in C
Why the following code return error when variable is declared global.
But if I call like this:
then it executes without an error.
- 5 File scope variables can only be initialised with constant expressions. A function call isn't one. – Daniel Fischer May 21, 2013 at 8:00
4 Answers 4
Initializers for global variables must be constant , they can't be an arbitrary expression.

In C language you cannot execute code in the global scope, outside a function and store the return value of the function in a global variable.
Global variables must be constant at initialisation, and when you're doing :
The return of the function is not constant.

From section 3.5.7 Initialization of the C standard:
All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.
and ab has static storage duration but add() is not a constant expression.
Global variables can be initialized by a constant expression . As their values are set at the compilation time , and not in run-time .

- s/constant value/constant expression/ – Jens May 21, 2013 at 8:14
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c function or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The [amazon] tag is being burninated
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Do you really get double penalized for rolling HSA excess contributions to the next year?
- Wahoo Kickr with 8 speed cassette?
- A limit involving the quotient of two sums
- A-Z related to countries
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Why are trials on "Law & Order" in the New York Supreme Court?
- How to react to a student’s panic attack in an oral exam?
- Can the Spiritual Weapon spell be used as cover?
- Recovering from a blunder I made while emailing a professor
- Minimising the environmental effects of my dyson brain
- Are 腹違い (harachigai) and 種違い (tanechigai) rude terms to use when referring to half-siblings?
- Should I use the mean or median of my data for queueing models?
- What is the purpose of this D-shaped ring at the base of the tongue on my hiking boots?
- Short story taking place on a toroidal planet or moon involving flying
- Experiment to crush soda can by air pressure
- How can I explain to my manager that a project he wishes to undertake cannot be performed by the team?
- Does Cosmic Background radiation transmit heat?
- Is there any way to orbit around the object instead of a 3D cursor?
- FAA Handbooks Copyrights
- Follow Up: struct sockaddr storage initialization by network format-string
- Prevent requests to 127.0.0.1 from being forwarded to http_proxy
- Acidity of alcohols and basicity of amines
- Which sentence is correct ? 我 对 欧洲 历史 很 熟悉 or 我 很 熟悉 欧洲 历史
- MAGENTO 2: PHP Parse error: syntax error, unexpected 'MageSuite' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) ... on line 7
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Vector in C++ STL
- Arrays in C/C++
- Initialize a vector in C++ (7 different ways)
- Map in C++ Standard Template Library (STL)
- std::sort() in C++ STL
- Bitwise Operators in C/C++
- The C++ Standard Template Library (STL)
- Inheritance in C++
- Object Oriented Programming in C++
- C++ Classes and Objects
- Multidimensional Arrays in C / C++
- Virtual Function in C++
- Set in C++ Standard Template Library (STL)
- Constructors in C++
- vector erase() and clear() in C++
- C++ Data Types
- Left Shift and Right Shift Operators in C/C++
- Substring in C++
- Converting Strings to Numbers in C/C++
- unordered_map in C++ STL
- Templates in C++ with Examples
- Socket Programming in C/C++
- Operator Overloading in C++
- Copy Constructor in C++
- rand() and srand() in C++
- 2D Vector In C++ With User Defined Size
- Stack in C++ STL
- getline (string) in C++
- Priority Queue in C++ Standard Template Library (STL)
- Sorting a vector in C++
std::string::assign() in C++
- Difficulty Level : Easy
- Last Updated : 28 Oct, 2020
The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str.
Output:
Syntax 2: Assigns at most str_num characters of str starting with index str_idx. It throws out_of _range if str_idx > str. size().
Syntax 3: Assign the characters of the C-string cstr. It throws length_error if the resulting size exceeds the maximum number of characters.
Syntax 4: Assigns chars_len characters of the character array chars. It throws length_error if the resulting size exceeds the maximum number of characters.
Syntax 5: Assigns num occurrences of character c. It throws length_error if num is equal to string::npos
Syntax 6: Assigns all characters of the range [beg, end). It throws length_error if range outruns the actual content of string.
This article is contributed by Sakshi Tiwari . If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...
- cpp-strings-library
Improve your Coding Skills with Practice
Start your coding journey now.
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
List assign() function in C++ STL
Given is th e task to show the working of the assign() function in C++.
The list::assign() function is a part of the C++ standard template library. It is used to assign the values to a list and also to copy values from one list to another.
<list> header file should be included to call this function.
The syntax for assigning new values is as follows −
The syntax for copying values from one list to another is as follows −
The function takes two parameters −
First is size, that represents the size of the list and the second one is value, which represents the data value to be stored inside the list.
Return Value
The function has no return value.
Explanation −
The following example shows how we can assign a list its size and values by using the assign() function. The first value that we will pass inside the list function becomes the size of the list, in this case it is 3 and the second element is the value that is assigned to each position of the list and here it is 10.
The following example shows how we can assign values to a list using an array. The total number of elements that we will assign to the list becomes the size of the list.
The user has to simply pass the name of the array as the first argument inside the assign() function, and the second argument should be the name of the array, then a “+” sign followed by the number of elements the user wants to assign to the list.
In the above case we have written 3, so the first three elements of the array will be assigned to the list.
If we write a number that is bigger than the number of elements present in the array, let us say 6, then the program will not show any error instead the size of the list will become 6 and the extra positions in the list will be assigned with the value zero.
Approach used in the below program as follows −
- First create a function ShowList(list<int> L) that will display the elements of the list.
- Create an iterator, let’s say itr that will contain the initial element of the list to be displayed.
- Make the loop run till itr reaches the final element of the list.
- Then inside the main() function create three lists using list<int> let’s say L1, L2 ad L3 so that they accept values of type int and then create an array of type int, let’s say arr[] and assign it some values.
- Then use the assign() function to assign size and some values to the list L1 and then pass the list L1 into the ShowDisplay() function.
- Then use the assign() function to copy elements of list L1 into L2 and also pass the list L2 into the ShowList() function.
- Then use the assign() function to copy elements of the array arr[] into the list L3 and pass the list L3 into the DisplayList() function.
Live Demo
If we run the above code it will generate the following output −
Explanation
For the list L1 we gave size as 3 and value as 20 in the assign() function which had generated the above output.
Then we copied the elements of list L1 into that L2 that gives L2 the same size and value as that of L1 as we can see in the output.
Then we used the assign function to copy all the elements of the array arr[] which made the size of L3 equal to 4 and its elements same as the elements of the array as in the output.

0 Followers
- Related Articles
- Forward list assign() function in C++ STL
- deque assign() function in C++ STL
- List push_front() function in C++ STL
- List reverse function in C++ STL
- List resize() function in C++ STL
- List push_back() function in C++ STL
- List pop_front() function in C++ STL
- List remove() function in C++ STL
- list empty() function in C++ STL
- list end() function in C++ STL
- list front() function in C++ STL
- list max_size() function in C++ STL
- list size() function in C++ STL
- list erase() function in C++ STL
- list merge() function in C++ STL

- <cassert> (assert.h)
- <cctype> (ctype.h)
- <cerrno> (errno.h)
- C++11 <cfenv> (fenv.h)
- <cfloat> (float.h)
- C++11 <cinttypes> (inttypes.h)
- <ciso646> (iso646.h)
- <climits> (limits.h)
- <clocale> (locale.h)
- <cmath> (math.h)
- <csetjmp> (setjmp.h)
- <csignal> (signal.h)
- <cstdarg> (stdarg.h)
- C++11 <cstdbool> (stdbool.h)
- <cstddef> (stddef.h)
- C++11 <cstdint> (stdint.h)
- <cstdio> (stdio.h)
- <cstdlib> (stdlib.h)
- <cstring> (string.h)
- C++11 <ctgmath> (tgmath.h)
- <ctime> (time.h)
- C++11 <cuchar> (uchar.h)
- <cwchar> (wchar.h)
- <cwctype> (wctype.h)
Containers:
- C++11 <array>
- <deque>
- C++11 <forward_list>
- <list>
- <map>
- <queue>
- <set>
- <stack>
- C++11 <unordered_map>
- C++11 <unordered_set>
- <vector>
Input/Output:
- <fstream>
- <iomanip>
- <ios>
- <iosfwd>
- <iostream>
- <istream>
- <ostream>
- <sstream>
- <streambuf>
Multi-threading:
- C++11 <atomic>
- C++11 <condition_variable>
- C++11 <future>
- C++11 <mutex>
- C++11 <thread>
- <algorithm>
- <bitset>
- C++11 <chrono>
- C++11 <codecvt>
- <complex>
- <exception>
- <functional>
- C++11 <initializer_list>
- <iterator>
- <limits>
- <locale>
- <memory>
- <new>
- <numeric>
- C++11 <random>
- C++11 <ratio>
- C++11 <regex>
- <stdexcept>
- <string>
- C++11 <system_error>
- C++11 <tuple>
- C++11 <type_traits>
- C++11 <typeindex>
- <typeinfo>
- <utility>
- <valarray>
class templates
- basic_string
- char_traits
- C++11 u16string
- C++11 u32string
- C++11 stold
- C++11 stoll
- C++11 stoul
- C++11 stoull
- C++11 to_string
- C++11 to_wstring
- string::~string
- string::string
member functions
- string::append
- string::assign
- C++11 string::back
- string::begin
- string::c_str
- string::capacity
- C++11 string::cbegin
- C++11 string::cend
- string::clear
- string::compare
- string::copy
- C++11 string::crbegin
- C++11 string::crend
- string::data
- string::empty
- string::end
- string::erase
- string::find
- string::find_first_not_of
- string::find_first_of
- string::find_last_not_of
- string::find_last_of
- C++11 string::front
- string::get_allocator
- string::insert
- string::length
- string::max_size
- string::operator[]
- string::operator+=
- string::operator=
- C++11 string::pop_back
- string::push_back
- string::rbegin
- string::rend
- string::replace
- string::reserve
- string::resize
- string::rfind
- C++11 string::shrink_to_fit
- string::size
- string::substr
- string::swap
member constants
- string::npos
non-member overloads
- getline (string)
- operator+ (string)
- operator<< (string)
- >/" title="operator>> (string)"> operator>> (string)
- relational operators (string)
- swap (string)
std:: string ::assign
Return value, iterator validity, exception safety.
cppreference.com
Assignment operators.
Assignment operators modify the value of the object.
[ edit ] Explanation
copy assignment operator replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is a special member function, described in copy assignment operator .
For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .
compound assignment operators replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .
[ edit ] Builtin direct assignment
The direct assignment expressions have the form
For the built-in operator, lhs may have any non-const scalar type and rhs must be implicitly convertible to the type of lhs .
The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a braced-init-list (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification. The result is a bit-field if the left operand is a bit-field.
For non-class types, the right operand is first implicitly converted to the cv-unqualified type of the left operand, and then its value is copied into the object identified by left operand.
When the left operand has reference type, the assignment operator modifies the referred-to object.
If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)
In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:
For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:
For every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:
[ edit ] Example
[ edit ] builtin compound assignment.
The compound assignment expressions have the form
The behavior of every builtin compound-assignment expression E1 op = E2 (where E1 is a modifiable lvalue expression and E2 is an rvalue expression or a braced-init-list (since C++11) ) is exactly the same as the behavior of the expression E1 = E1 op E2 , except that the expression E1 is evaluated only once and that it behaves as a single operation with respect to indeterminately-sequenced function calls (e.g. in f ( a + = b, g ( ) ) , the += is either not started at all or is completed as seen from inside g ( ) ).
In overload resolution against user-defined operators , for every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:
For every pair I1 and I2, where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:
For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:
[ edit ] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
[ edit ] See also
Operator precedence
Operator overloading
- Todo no example
- Recent changes
- Offline version
- What links here
- Related changes
- Upload file
- Special pages
- Printable version
- Permanent link
- Page information
- In other languages
- This page was last modified on 21 November 2022, at 04:25.
- This page has been accessed 357,612 times.
- Privacy policy
- About cppreference.com
- Disclaimers

- BYJU'S GATE
- GATE Study Material
- GATE Notes For CSE
- Introduction To C Programming
Function Pointer in C

One can create pointers in the C language of any data type, like char, int, float, etc. Similarly, it is easy to create pointers that point to various functions in the C language.
In this article, we will take a look at the function pointer in C and its uses according to the GATE Syllabus for CSE (Computer Science Engineering) . Read ahead to learn more.
Table of Contents
What is a Function Pointer in C?
The process of declaration of the function pointers.
- Calling of a Function through the Function Pointer in C
The Passing of the Function Address to Another Function as an Argument
Function pointer arrays, functions that return pointer variables, safe ways in which we can return a pointer that is valid, examples of complicated types of function pointers.
- Practice Problems On Function Pointer in C
The use of pointers as function parameters is to hold (point at) the addresses of various arguments that are passed during the function calls. It is termed a call by reference. Thus, whenever a function gets called by reference in a program, any changes that we make on the reference variable would have a direct impact on its original value.
A function’s code resides in the memory. It means that every function has an address of its own. Also, we can use the function pointer to get the exact address of this memory.
Example for Function Pointer in C
Let us look at an example for the same.
#include <stdio.h>
printf(“The address of the main() function in this program is %p as in function pointers”,main);
The code mentioned here above prints the main() function’s address in the program.
The output of the code mentioned above would be:
The address of the main() function in this program is 0x400536 as in function pointers
In the output mentioned above, we can observe that this main() function consists of an address of its own. Thus, it can be concluded that each function consists of a unique address of its own.
Now that you are aware that every function consists of an address, one can create various pointers consisting of these addresses (storing the addresses), and thus, it can point at them in a program.
return type (*pointer_name)(type_A, type_B… type_Z);
Let us take a look at an example to understand this better:
int (*ip) (int);
The declaration mentioned above has a pointer *ip pointing to a function. It returns a certain int (integer) value and also accepts an integer in the form of an argument. Now let us take a look at another example.
float (*fp) (float);
The declaration mentioned above consists of a pointer *fp pointing towards a certain function. It returns some float (floating) value as it accepts the argument in the form of a float value.
Observe that the declaration of any given function in a program is very similar to how we declare its function pointer. the only difference here is that the pointers to functions are preceded by the symbol ‘*’. Thus, in the case mentioned above, the declaration of fp occurs in the form of a function, and not in the form of a pointer.
Now that we have uncovered how one can declare a function pointer, the next step would be to assign these function pointers with separate addresses.
float (*ip) (int , int); // Declaring the function pointer in the program
float funct ( int , int ); // Declaring the function in the program
ip = funct; // We assign the address of the funct to the pointer ip
The pointer ‘ip’ in the declaration mentioned above consists of the ‘funct’ function’s address in the program.
Note that the declaration of functions is a prerequisite before you assign the function pointer with the available function’s address.
Calling of a Function with the Function Pointer in C
Till now, we have discussed how we can call any function in a general way. Next, we will discuss how we can use the function pointer to call any function in a program.
Let us suppose that we declare any given function as follows:
float funct(int , int); // Declaring a function in the program
Here is how we can call the above function in a very usual way:
result = funct( x , y ); // We call the function using the usual way
Here is how we can call a function with the use of the function pointer:
result = (*fp)( x , y ); // We call the function with the use of function pointers
result = fp( x , y ); // We call the function with the use of function pointer, and we can remove the indirection operator
When we call a function by its own name, it has the same effect as calling it using its function pointer. When using the function pointers, one can take a step ahead and omit the indirection operator, just like we have portrayed in the second case. Yet, we can utilise the indirection operator since it makes it very clear to all the users that they can use a function pointer.
We will take a look at an example to better understand function pointers in C:
int sub(int,int); // Mentioning the subtraction of values
int (*fp)(int,int); // Generating the output
int output;
printf(“Here, we enter the actual values of the variables x and y : “);
scanf(“%d %d”,&x,&y);
result=(*fp)(x,y);
printf(“The total value of the final variable after subtracting one variable from the other one is equal to : %d”,output);
int sub(int x,int y)
The output obtained from the code mentioned above would be:
Here, we enter the actual values of the variables x and y : 38 26
The total value of the final variable after subtracting one variable from the other one is equal to : 12
One can pass the address of a function to another function in the form of an argument the exact way we send an argument to a function in a program.
Let us take a look at an example to understand this better.
include <stdio.h>
void func_A (void (*pntr)());
void func_B ();
func_A (func_B);
void func_A (void (*pntr)())
printf(“The function A is known as”);
void func_B ()
printf(“\nThe function B is known as”);
The output obtained from the code mentioned above would be as follows:
The function A is known as
The function B is known as
In the code mentioned above, we have created two separate functions- the func_A and the func_B. Here, the func_A consists of the function pointer in the form of an argument. This func_A method gets called in the main() method- in which we will be passing the func_B address. The ptr consists of this address of func_B when we call the func_A. Thus, we call the function func_B inside the function func_A by dereferencing the ptr pointer, since it consists of the func_B function’s actual address.
We use the function pointers in those applications where we don’t know which of the functions will be called (we don’t know in advance). In the case of an array of various function pointers, the array would take the address of all the functions. After this, the calling of the most appropriate function will occur on the basis of the index number.
We will take a look at this with the help of a simple example. Here is how:
float div (int,float);
float mul (int,float);
float sub (int,float);
float add (int,float);
float a; // declaration of a variable
float (*ip[4]) (int,float); // declaration of the function pointer
ip[0]= div; // we assign addresses to all the elements of the array of all function pointers
ip[1]= mul;
ip[2]= sub;
ip[3]= add;
printf(“Please enter the respective values of the variables a and b : “);
scanf(“%f %d”,&a,&b);
float j=(*ip[0]) (a,b); // We are calling the div() function in the program
printf(“\nThe division of the two values will generate the result : %f”,j);
j=(*ip[1]) (a,b); // We are calling the mul() function in the program
printf(“\nThe multiplication of the two values will generate the result : %f”,j);
j=(*ip[2]) (a,b); // We are calling the sub() function in the program
printf(“\nThe difference between the two values will generate the result : %f”,j);
j=(*ip[3]) (a,b); // We are calling the add() function in the program
printf(“\nThe addition of the two values will generate the result : %f”,j);
float div(float a,int b)
float t=a/b;
float mul(float a,int b)
float t=a*y;
float sub(float a,int b)
float t=a-b;
float add(float a,int b)
float t=a+b;
In the code mentioned above, we have actually created an array of various function pointers consisting of the addresses of all the four functions. Once we store the addresses of all these functions in the function pointers’ array, we then use the function pointers to call their respective functions.
The output obtained out of the code mentioned above would be:
Please enter the respective values of the variables a and b : 5 4
The division of the two values will generate the result : 1.250000
The multiplication of the two values will generate the result : 20.000000
The difference between the two values will generate the result : 1.000000
The addition of the two values will generate the result : 9.000000
The functions in a program are also capable of returning a pointer that points towards the calling function. But be very careful in this case. It is because the function’s local variables don’t reside out of it. They rather have their scope inside the functions themselves. Thus, if we return the pointers connected to the local variables, that particular pointer would point towards nothing at all when this function would end.
int* larger(int*, int*);
void main()
int p = 15;
int q = 92;
x = larger(&p, &q);
printf(“The number %d is larger in value”,*x);
int* larger(int *a, int *b)
if(*a > *b)
The output obtained out of the function mentioned above would be:
The number 92 is larger in value
- We use the arguments along with the functions. We can do so because the declaration of all the arguments that pass on to the functions occurs inside the calling functions. Thus, these will also reside outside the given function.
- Conversely, we can also make use of the static local variables inside the available functions and then return them. Here, since the static variables have a complete lifetime in which the main() function would exist, these will be thus available throughout any program.
We will understand the concept of complicated function pointers with the help of an example here. Let us see how:
void *(*foo) (int*);
Now, this one would appear complex- but it is actually very simple in reality. Here, in this case, the (*foo) is acting as a pointer towards that function in which the argument is of the type int* while the return type here is void*.

Practice Problems on Function Pointer in C
1. What would be the output obtained out of the program mentioned below?
int sum(int a, int b)
return a+b;
int main( )
int (*fp)(int, int);
fp = total;
int t = fp(10, 15);
printf(“The output of both the numbers is equal to %d”, t);
A. The output of both the numbers is equal to 15
B. The output of both the numbers is equal to 10
C. The output of both the numbers is equal to 25
D. The output of both the numbers is equal to 5
Answer: C. The output of both the numbers is equal to 25
2. What would be the output obtained out of the program mentioned below?
int g = 44;
int h = 87;
n = smaller(&g, &h);
printf(“The number %d is comparatively smaller in value”,*n);
int* larger(int *r, int *s)
if(*r > *s)
A. The number is comparatively smaller in value
B. The number 44 is comparatively smaller in value
C. 44 The number is comparatively smaller in value
D. The number 44 is comparatively smaller in value
Answer: D. The number 44 is comparatively smaller in value
Frequently Asked Questions
When do we use an array of function pointers in a c program.
We use the function pointers in those applications in which we don’t know which of the functions will be called (we don’t know in advance). In the case of an array of various function pointers, the array would take the address of all the functions. After this, the calling of the most appropriate function will occur on the basis of the index number.
Why do we use pointers in the C language?
The use of pointers as function parameters is to hold (point at) the addresses of various arguments that are passed during the function calls. It is termed a call by reference. Thus, whenever a function gets called by reference in a program, then any changes that we make on the reference variable would have a direct impact on its original value. A function’s code resides in the memory. It means that every function has an address of its own. Also, we can use the function pointer to get the exact address of this memory.
Keep learning and stay tuned to get the latest updates on GATE Exam along with GATE Eligibility Criteria , GATE 2023 , GATE Admit Card , GATE Syllabus for CSE (Computer Science Engineering) , GATE CSE Notes , GATE CSE Question Paper , and more.
Also Explore,
- Data Types in C
- Double Data Type in C
- Enumerated Data Type in C
- Formatted Input and Output in C Pointers in C
- Decision Control Statement in C
- Factorial Program in C Using Recursion
- Function in C
Leave a Comment Cancel reply
Your Mobile number and Email id will not be published. Required fields are marked *
Request OTP on Voice Call
Post Comment

Connect with us for GATE Preparation
Register now to get complete assistance for the gate 2022 exam.
- Share Share
Register with BYJU'S & Download Free PDFs
C Functions
C structures, c variables.
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
- int - stores integers (whole numbers), without decimals, such as 123 or -123
- float - stores floating point numbers, with decimals, such as 19.99 or -19.99
- char - stores single characters, such as 'a' or 'B' . Char values are surrounded by single quotes
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value :
Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName ). The equal sign is used to assign a value to the variable.
So, to create a variable that should store a number , look at the following example:
Create a variable called myNum of type int and assign the value 15 to it:
You can also declare a variable without assigning the value, and assign the value later:
Output Variables
You learned from the output chapter that you can output values/print text with the printf() function:
In many other programming languages (like Python , Java , and C++ ), you would normally use a print function to display the value of a variable. However, this is not possible in C:
To output variables in C, you must get familiar with something called "format specifiers".
Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of data the variable is storing. It is basically a placeholder for the variable value.
A format specifier starts with a percentage sign % , followed by a character.
For example, to output the value of an int variable, you must use the format specifier %d or %i surrounded by double quotes, inside the printf() function:
To print other types, use %c for char and %f for float :
To combine both text and a variable, separate them with a comma inside the printf() function:
To print different types in a single printf() function, you can use the following:
You will learn more about Data Types in the next chapter .
Change Variable Values
Note: If you assign a new value to an existing variable, it will overwrite the previous value:
You can also assign the value of one variable to another:
Or copy the value of one variable and assign it to a variable without a value:
Or copy values to empty variables:
Add Variables Together
To add a variable to another variable, you can use the + operator:
Declare Multiple Variables
To declare more than one variable of the same type, use a comma-separated list:
You can also assign the same value to multiple variables of the same type:
C Variable Names
All C variables must be identified with unique names .
These unique names are called identifiers .
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable code:
The general rules for naming variables are:
- Names can contain letters, digits and underscores
- Names must begin with a letter or an underscore (_)
- Names are case sensitive ( myVar and myvar are different variables)
- Names cannot contain whitespaces or special characters like !, #, %, etc.
- Reserved words (such as int ) cannot be used as names
Real-Life Example
Often in our examples, we simplify variable names to match their data type (myInt or myNum for int types, myChar for char types etc). This is done to avoid confusion.
However, if you want a real-life example on how variables can be used, take a look at the following, where we have made a program that stores different data of a college student:
C Exercises
Test yourself with exercises.
Create a variable named myNum and assign the value 50 to it.
Start the Exercise

COLOR PICKER

Get certified by completing a course today!

Certificates
Report error.
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.

Introduction to C++ null
The null function is used to assign value to the variable; this can be treated as the default value for the variable defined in many programming languages. Null functions can be used to assign value to a pointer that is not pointing to any address and contain any garbage value, so the null function will assign them a special value called ‘NULL’, which means they are now null pointer. In this topic, we are going to learn about C++ null.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
This is very simple to assign a null value to the variable in C++; we just need to do this at the time of initialization only. This variable then turns to be treated as the Null pointer. Below see the syntax to understand this better and used while programming see below;
In the above syntax, we are using the NULL value here to assign to a pointer. First, we have to define the pointer, and then we can initialize it with NULL. Sample practice syntax for more understanding see below;

How does the null function work in C++?
As of now, we know that we use Null functions to assign some special value to the pointer variable. By the use of this, we can give them a logical value when they are not pointing to any address in the memory. That’s why it is also known as a special value to the pointer. Also, we know that pointer holds the memory address, so if we want them to point to some other value, in that case, we can use NULL here. But we have to use this while initiation of the pointer. Now we will see one example and understand its working how it actually works; for more detail, see below;
In this example, we create three different pointers, and all of them point to the NULL here. So as we can see, we have initialized the value for the variable at the time of declaring the variables. After this, we are making one check here to check and print the value of the pointer. If the statement coming out to be right, then the print statement will be executed; otherwise, it will return. If we see it will assign a default value of ‘0’ to the pointer. So a null can be an integer value as well when it is not pointing to the memory address. In the if statement above, as you can see pointer is pointing to null, but here it got converted into Boolean false, and if the value for any of the pointers is not null, then it will convert into Boolean true.
So in this way, we can test our pointers as well. Null functions are nothing but a way to assign value to the pointer variable in c++. We can also do dereferencing of our null pointers in c++, but this will lead to unusual behavior of the program. this is because dereferencing means go back to the previous state where it is pointing to before initiation, but if we try to do this in our code, a null pointer still points nowhere because it has no memory address attached with it.
Points to be remembered while working with the NULL functions in c++ see below;
1) We have to assign the null value to the pointer at the time of initiation only.
2) If the pointer does not point to any memory address in C++, it does not point to null; we will use NULL functions to assign them value.
3) If we assign a value to a pointer using null functions, then they will convert to Boolean true or false depending on the value they are holding. This is because the null pointer can be integer also.
Examples of C++ null
Given below are the examples of C++ null:
In this example, we will see how to initialize the null value to the pointer using the NULL function in C++; this is nothing but the special value we can assign at the time of initialization. There is no particular syntax to do this.

In this example, we are going to see how to make a conditional statement while using a NULL pointer in your program and how they change the value while checking them. After the statement, we are assigning them a new value to the point.

Hence we can use null functions to assign value to the variable; null values are important when our pointer is not pointing to any memory address to avoid the unusual behavior while programming, so null functions or null assigning to a pointer is used to assign a default value when they are not pointing anywhere in the memory address.
Recommended Articles
This is a guide to C++ null. Here we discuss how the null function works in C++ and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –
- C++ static_cast
- C++ Read File
- C++ Lambda Expressions
- C++ Aggregation

Related Courses

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept
By signing up, you agree to our Terms of Use and Privacy Policy .
Forgot Password?
This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Explore 1000+ varieties of Mock tests View more
Submit Next Question


Inline Functions in C++
Looking for more C++ related resources? Explore other blog posts in the series —
- Virtual Functions in C++
- Constructors in C++
- Constant Variables in C++
Moving on from C, the C++ programming language introduced a new keyword called inline. This new keyword can be used to qualify C++ functions which then serves as an alternative to C language’s parameterized macros. In this article, we will be seeing how to create inline functions in C++ and how are they an improvement over C’s parameterized macros.
Macros with Parameters
You may be familiar with macros if you have C language programming knowledge. Macro definitions in C and C++ are done using the #define syntax. These macros are like aliases and are textually substituted before the compilation process by C Pre-Processor. Here is an example of paramterized macros in use.
The way we define and use the SQUARE macros makes it look like a function. But this is not what happens. Under the hood, the C Pre-Processor would replace all the occurence of SQUARE with macro definition. This is what our code will look like after processing by C Pre-Processor.
Pitfalls of Macros
There are several pitfalls of using parameterized macros. Following is just one example of many cases where such definitions don’t work as expected.
In the above example, the code execution results in 7 being printed to the output console. This is because macros are not functions and they are simply replaced by CPP. So after C Pre-Processor (CPP) completes its processing, the code would look like this.
inline Functions
An inline function is just like any other function in C++. The only difference between a normal C++ function and an inline C++ function is that the inline C++ function will not involve a stack call. An inline function is expanded (inlined) at the site of its call and the overhead of passing parameters between caller and callee (or called) functions is avoided.
Using inline function to write the same code above would result in the following.
To create an inline function, we prefix a function prototype with the inline keyword.
Advantages of inline functions
There are several advantages associated with using inline functions. Some of them are —
- There are no syntactic or semantic pitfalls that are present in macros.
- Type checking for parameters is performed.
- Functions can be analysed through a debugger.
We need to understand that inline is just a directive to the compiler. The compiler may or may not expand the function at the place of call. The compiler uses the body size of the function to decide whether to expand in place.
Another limitation is that inline functions can not be recursive.
That is it for this byte-sized learning packet for you. If you enjoy reading such articles, consider following and subscribing to my news letter so that you do not miss on related articles in future.
More from Rishabh Agarwal
Software Engineer at Schrödinger India!
About Help Terms Privacy
Get the Medium app

Rishabh Agarwal
Text to speech

IMAGES
VIDEO
COMMENTS
You can't assign to an array. Two solutions: either copy the string: strcpy (a.name, "Markson"); or use a const char pointer instead of an array and then you can simply assign it: struct { const char *name; /* etc. */ }; a.name = "Markson"; Or use a non-const char pointer if you wish to modify the contents of "name" later:
In C language you cannot execute code in the global scope, outside a function and store the return value of the function in a global variable. Global variables must be constant at initialisation, and when you're doing : x = func ( ... ) The return of the function is not constant. Share Improve this answer Follow answered May 21, 2013 at 8:00
A function is a group of statements that together perform a task. Every C program has at least one function, which is main (), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
vector:: assign () is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary. The syntax for assigning constant values: vectorname.assign (int size, int value) Parameters: size - number of values to be assigned value - value to be assigned to the vectorname
The member function assign () is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this CPP #include <iostream> #include <string> using namespace std;
The list::assign () function is a part of the C++ standard template library. It is used to assign the values to a list and also to copy values from one list to another. <list> header file should be included to call this function. Syntax The syntax for assigning new values is as follows − List_Name.assign (size,value) Syntax
Assigns a new value to the string, replacing its current contents. (1) string Copies str. (2) substring Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos). (3) c-string Copies the null-terminated character sequence (C-string) pointed by s.
For the built-in operator, lhs may have any non-const scalar type and rhs must be implicitly convertible to the type of lhs. The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a braced-init-list (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification.
Function Pointer in C: The use of pointers as function parameters is to hold (point at) the addresses of various arguments that are passed during the function calls. ... Note that the declaration of functions is a prerequisite before you assign the function pointer with the available function's address. Calling of a Function with the Function ...
In C, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123 float - stores floating point numbers, with decimals, such as 19.99 or -19.99 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
1) We have to assign the null value to the pointer at the time of initiation only. 2) If the pointer does not point to any memory address in C++, it does not point to null; we will use NULL functions to assign them value. 3) If we assign a value to a pointer using null functions, then they will convert to Boolean true or false depending on the ...
30 seconds. 1 pt. Q. Can operator overloading be used to create new operators in C++? answer choices. Yes, operator overloading can be used to create new operators in C++. No, operator overloading cannot be used to create new operators in C++. The creation of new operators is only possible in C++ through the use of macros.
An inline function is just like any other function in C++. The only difference between a normal C++ function and an inline C++ function is that the inline C++ function will not involve a stack call.