The most ancient sacred literature of Hinduism is called the Vedas. This collection of hymns, poems, and ceremonial formulas represent the beliefs of several Aryan tribes. Initially the Vedas were considered so sacred that they were only transmitted orally from one generation of brĂ¢hmans to the next. The passages of the Vedas were eventually written in Sanskrit, we believe, near the end of the third century BC, and primarily consist of four collections called the Rig-Veda, the Sama-Veda, the Yajur-Veda, and the Atharva-Veda. Collectively, these are referred to as the Samhitas.
The first three Samhitas were used in the Vedic period by the priestly class as ritual handbooks. Containing 1,028 poetic hymns, the Rig-Veda was used by the hotri who called on the gods by reciting the hymns aloud. The hymns vary in style and length, and praise a pantheon of gods. Although Indra, the god of war and weather, is the most frequently mentioned, there appears to be no hierarchy. Agni, the god of fire, is the second most prominently mentioned deity. The Sama-Veda consisted of various portions taken from the Rig-Veda and were utilized by the udgatri chanters. The Yajur-Vedas was used by the adhvaryu priests. This work contains specific sacrificial formulas which were recited during that form of ceremony.
The final Veda, the Atharva-Veda, is attributed to a sage, or rishi, named Atharvan, and consists of a number of hymns and magical incantations. Some scholars believe that this scripture may have originated with the original pre-Aryan culture of indigenous peoples, and because it deviated form the other Vedas, it was not at first readily accepted. Eventually it too was adopted as a ritual handbook by the Brahmans, the higest class of priests.
Although the Rig-Veda is still considered the most important of these ancient texts, it was still never very popular. Much of this comes from the fact of its composition by and for a religious aristocracy. In contrast, the Atharva-Veda, compiled perhaps as late as 500 BC, frequently refers to many lesser functional gods considered useful in the daily lives and simple rituals of the ordinary Aryan that did not need the mediation of priests.
Monday, December 22, 2008
Monday, December 15, 2008
The Vedic Age: Part-II
Between 800 and 400 BC, significant changes began to occur in the lives of religious peoples in all of the civilized parts of the world. Independent thinkers, discontented with the traditional explanations of the cosmic order, and specifically man's place within that cosmos, began to develop new, more simple and rational, doctrines. Scholars frequently refer to this period as the Axial Age. There is, however, no solid explanation why such dramatic religious changes would occur throughout the world during the same period.
Prominent among the rising sages were the Greek philosophers led by Socrates. In Persia, Zarathustra extracted the elements of the supernatural from religion and created a new faith, Zoroastrianism. In China, Confucius devoted himself to teaching moral persuasion and good government, which would become the mainstay of Chinese thought. The Hebrew prophets formulated a monotheistic religious tradition notably different from the polytheistic religions of Greece, China, Mesopotamia, and India. While all of this was happening in the rest of the world, kshatriya ascetics, throughout India, began to challenge the proliferation of brahmin ritual that personified the Aryan religion of the Vedic Age.
During this time, the Vedas were still held in high regard, but this new generation of seekers sought a more enlightened meaning to life. This period is commonly referred to as the Vedantic Age. The collection of teachings generated by the ascetics who meditated on the mysteries of human existence became known as the Upanishads, and the seekers who produced the writings were called Upanishads, which literally means "sitting near" the gurus. Over a hundred Upanishads have survived, but only a dozen, or so, are considered authentic. To lend credibility to the teachings, they were invariably compiled as appendages to the Vedas. Vedanta, then, means the "end of the Vedas." In this respect, the Vedas are considered the foundation of the faith while the Upanishads are considered the vehicle whereby the devotee may attain enlightenment as to the nature of god and man's role in the cosmos.
Scholars continue to debate over the beginning of Hinduism. Some insists that this tradition began with the Indus civilization and its proto-Shiva personified by the horned god. Others point to the development of the Aryan religion of the Vedic Age as the genesis of the Hindu tradition. Still others point to the Vedantic Age, with the development of karma (deed), and the doctrine of samsara or the transmigration of birth and rebirth, as the fundamental beginning. Unfortunately, unlike many other religions, Hinduism can not be attributed to the teachings of any single individual. This sort of ambiguity naturally lends itself to debate and speculation.
Although we are unable to accurately date the beginning of Hinduism, we can point to the Vedantic Age as the period in Indian history where the Hindu religious tradition began to solidify. The principles of karma and samsara directly appealed to a populace caught in the stranglehold of the rigidity of the caste system. In this respect, one's deeds in the present life would directly effect their future as the soul passes form life to life.
Interestingly, the Upanishads, nor the thinkers reponsible for the new orthodoxy of the Hindu religion, ever directly challenged the Vedic beliefs, the existing gods, or the practice of sacrifice. Instead, a quiet transformation gradually occurred that formulated a new system of thought that became the cornerstone of Hinduism. Increasingly, the common people directed their faith toward lesser deities that filled their specific needs. Rising to the top of the nonexistent hierarchy of the gods, the religious practices, although still based in the Vedic scripture, decidedly shifted from Indra and Varuna to the two current sects of Hinduism which worship Vishnu and Shiva.
Prominent among the rising sages were the Greek philosophers led by Socrates. In Persia, Zarathustra extracted the elements of the supernatural from religion and created a new faith, Zoroastrianism. In China, Confucius devoted himself to teaching moral persuasion and good government, which would become the mainstay of Chinese thought. The Hebrew prophets formulated a monotheistic religious tradition notably different from the polytheistic religions of Greece, China, Mesopotamia, and India. While all of this was happening in the rest of the world, kshatriya ascetics, throughout India, began to challenge the proliferation of brahmin ritual that personified the Aryan religion of the Vedic Age.
During this time, the Vedas were still held in high regard, but this new generation of seekers sought a more enlightened meaning to life. This period is commonly referred to as the Vedantic Age. The collection of teachings generated by the ascetics who meditated on the mysteries of human existence became known as the Upanishads, and the seekers who produced the writings were called Upanishads, which literally means "sitting near" the gurus. Over a hundred Upanishads have survived, but only a dozen, or so, are considered authentic. To lend credibility to the teachings, they were invariably compiled as appendages to the Vedas. Vedanta, then, means the "end of the Vedas." In this respect, the Vedas are considered the foundation of the faith while the Upanishads are considered the vehicle whereby the devotee may attain enlightenment as to the nature of god and man's role in the cosmos.
Scholars continue to debate over the beginning of Hinduism. Some insists that this tradition began with the Indus civilization and its proto-Shiva personified by the horned god. Others point to the development of the Aryan religion of the Vedic Age as the genesis of the Hindu tradition. Still others point to the Vedantic Age, with the development of karma (deed), and the doctrine of samsara or the transmigration of birth and rebirth, as the fundamental beginning. Unfortunately, unlike many other religions, Hinduism can not be attributed to the teachings of any single individual. This sort of ambiguity naturally lends itself to debate and speculation.
Although we are unable to accurately date the beginning of Hinduism, we can point to the Vedantic Age as the period in Indian history where the Hindu religious tradition began to solidify. The principles of karma and samsara directly appealed to a populace caught in the stranglehold of the rigidity of the caste system. In this respect, one's deeds in the present life would directly effect their future as the soul passes form life to life.
Interestingly, the Upanishads, nor the thinkers reponsible for the new orthodoxy of the Hindu religion, ever directly challenged the Vedic beliefs, the existing gods, or the practice of sacrifice. Instead, a quiet transformation gradually occurred that formulated a new system of thought that became the cornerstone of Hinduism. Increasingly, the common people directed their faith toward lesser deities that filled their specific needs. Rising to the top of the nonexistent hierarchy of the gods, the religious practices, although still based in the Vedic scripture, decidedly shifted from Indra and Varuna to the two current sects of Hinduism which worship Vishnu and Shiva.
Friday, December 12, 2008
The Vedic Age: Part-I
What little we know of the Vedic Age comes from the Rig-Veda. By the time the oral tradition of the Aryan religion was comitted to Sanskrit, however, some of the gods mentioned had already begun to lose their importance. Nevertheless, The Rig-Veda represented a blend of beliefs held by several Aryan tribes.
Each of the gods, of the Vedic Period, had a primary function, or Vrata. Usually these functions were closely connected to the forces of nature such as light, fire, and heaven which in turn followed the cosmic order (rta) of the universe. The demons of darkness and chaos, headquartered under the earth, arrayed their power against the righteousness of the gods. In this dualistic approach, the demons sought to disrupt the system of nature, therefore practicing anrta. During a later period, rta gave way to the concept of dharma, which could be translated as "virtue."
Although the deities of the Rig-Veda are not organized hierarchically, each could, in its own right, be looked upon as the supreme god. Nevertheless, Indra, the god of war and weather, receives the most attention in the ancient Vedic text, and is frequently referred to as the eka deva, or "one god." According to the Rig-Veda (6.7), creation began once Indra slew Vritra, the serpent demon, who had locked up the waters necessary for human existence in mountain caves. With the waters now released, he then placed the sun in the sky thus establishing the cosmic order (rta) under the god Varuna.
Varuna, then, sits in the palace of heaven and oversees the world below. As the guardian of the moral order, both earthly and cosmic, Varuna punishes the sinner with disease, or for all time by condemning them to the House of Clay following death. Aryans who practiced right deeds, or performed the proper ritual would forever celebrate happiness after death. Varuna is aided in his efforts by many spies who fly through the cosmos at his command.
Less important than Indra, but still held in high regard among the numerous deities of the Aryan religion, was Agni, the fire god. Agni descends from the darkened clouds as lightning, shines on the world as the sun, and manifests in the flame of the sacrifice. Through the sacrificial offering, Agni served as the intermediary between the gods and man, and the correct performance of this important ritual could beneficially reward the devotee. Rituals based on the fire sacrifice could be as personal as dumping clarified butter in the family hearth, to the production of soma juice. As part of the sacrificial ritual, parts of the soma plant were pressed between stones, mixed with milk, and filtered through a sheepskin. An hallucinogen, soma consumed during sacrifices supposedly produced a sense of superhuman strength and visions of the gods. Soma would later become the moon god.
The cosmic order of the Aryan universe remained fairly simple. The heavens served as the residence of the major gods and the souls of the righteous. The region between heaven and earth was called the antariksa. This region, where the birds flew and the clouds crossed the sky, was also home to the demigods. Below the earth, in the darkness of the House of Clay, dwelled the spirits of the unrighteousness and the demons that sought to disrupt rta. The concept of birth and rebirth had not yet become part of the Indian cosmology that would later be indicative of all Indian religion.
Religion during the Vedic Age revolved around the sacrifice. Within the home, the patriarch of the family daily sacrificed at the domestic hearth while the brahmans performed great rituals slaughtering numerous animals to the gods. In each case, the idea was to communicate with the gods who would descend from the heavens granting the devotees health, happiness, and success. Over time, these rituals became so complex that the brahmans, who knew the correct ritual, became indispensable.
Each of the gods, of the Vedic Period, had a primary function, or Vrata. Usually these functions were closely connected to the forces of nature such as light, fire, and heaven which in turn followed the cosmic order (rta) of the universe. The demons of darkness and chaos, headquartered under the earth, arrayed their power against the righteousness of the gods. In this dualistic approach, the demons sought to disrupt the system of nature, therefore practicing anrta. During a later period, rta gave way to the concept of dharma, which could be translated as "virtue."
Although the deities of the Rig-Veda are not organized hierarchically, each could, in its own right, be looked upon as the supreme god. Nevertheless, Indra, the god of war and weather, receives the most attention in the ancient Vedic text, and is frequently referred to as the eka deva, or "one god." According to the Rig-Veda (6.7), creation began once Indra slew Vritra, the serpent demon, who had locked up the waters necessary for human existence in mountain caves. With the waters now released, he then placed the sun in the sky thus establishing the cosmic order (rta) under the god Varuna.
Varuna, then, sits in the palace of heaven and oversees the world below. As the guardian of the moral order, both earthly and cosmic, Varuna punishes the sinner with disease, or for all time by condemning them to the House of Clay following death. Aryans who practiced right deeds, or performed the proper ritual would forever celebrate happiness after death. Varuna is aided in his efforts by many spies who fly through the cosmos at his command.
Less important than Indra, but still held in high regard among the numerous deities of the Aryan religion, was Agni, the fire god. Agni descends from the darkened clouds as lightning, shines on the world as the sun, and manifests in the flame of the sacrifice. Through the sacrificial offering, Agni served as the intermediary between the gods and man, and the correct performance of this important ritual could beneficially reward the devotee. Rituals based on the fire sacrifice could be as personal as dumping clarified butter in the family hearth, to the production of soma juice. As part of the sacrificial ritual, parts of the soma plant were pressed between stones, mixed with milk, and filtered through a sheepskin. An hallucinogen, soma consumed during sacrifices supposedly produced a sense of superhuman strength and visions of the gods. Soma would later become the moon god.
The cosmic order of the Aryan universe remained fairly simple. The heavens served as the residence of the major gods and the souls of the righteous. The region between heaven and earth was called the antariksa. This region, where the birds flew and the clouds crossed the sky, was also home to the demigods. Below the earth, in the darkness of the House of Clay, dwelled the spirits of the unrighteousness and the demons that sought to disrupt rta. The concept of birth and rebirth had not yet become part of the Indian cosmology that would later be indicative of all Indian religion.
Religion during the Vedic Age revolved around the sacrifice. Within the home, the patriarch of the family daily sacrificed at the domestic hearth while the brahmans performed great rituals slaughtering numerous animals to the gods. In each case, the idea was to communicate with the gods who would descend from the heavens granting the devotees health, happiness, and success. Over time, these rituals became so complex that the brahmans, who knew the correct ritual, became indispensable.
Wednesday, December 10, 2008
The Pre-Vedic age
Very little is known about the religion of the Indus civilization because no written records exit. There is, however, an assumption that parts of the Harappan tradition were held in common by ancient religions of the Middle East as well as the later Hinduism. Prominent among the evidence discovered are the many seals discovered at the sites along the Indus River, as well as in Mesopotamia. Some of these seals clearly indicate the sacredness of the bull which later became a common tradition in Hinduism. Other features are the horned god. These seals have two faces in profile, and one facing forward. The figure is surrounded by a tiger, an elephant, a rhinoceros, and a buffalo. His legs are bent with his feet pressed together in a yoga position which has led some to believe that this god is most likely a proto-Shiva. Shiva is the three-faced Hindu god of death, destruction, and fertility.
Some of these sites have also yielded terra-cotta figurines. Similar, in many respects, to evidence discovered in Egypt and Iran, some of these figurines are of broad-hipped pregnant-looking females. Representative of the Great Mother or nature, these types of deities, as well as the bull, are common among early agricultural societies of Eurasia.
Excavations of Indus cities have not revealed any buildings that can positively be identified as temples. No large statues or monumental sculptures, similar to those found in Egypt, have been discovered. This lack of temples and statuary has resulted in the belief that the focus of religious life was primarily centered in the home. Anthropologists are relatively certain that the peoples of the Indus civilization emphasized ritual purity. Much of this is evidenced by the presence of drainable baths in most of the residences, as well as a great bath or pool surrounded by a pillared hall with small cell-like rooms. Scholars have surmised that washing and bathing were integral to the preservation of purity and that cleanliness was considered necessary to ward off evil spirits.
Similar to the culture of Egypt, it appears that the Indus religion recognized some type of life after death. Unlike later Indians, who practiced cremation, this civilization carefully buried their dead with their heads facing north and the feet pointing south. Included in the graves were pottery jars containing food and weapons for use in the afterlife.
Some of these sites have also yielded terra-cotta figurines. Similar, in many respects, to evidence discovered in Egypt and Iran, some of these figurines are of broad-hipped pregnant-looking females. Representative of the Great Mother or nature, these types of deities, as well as the bull, are common among early agricultural societies of Eurasia.
Excavations of Indus cities have not revealed any buildings that can positively be identified as temples. No large statues or monumental sculptures, similar to those found in Egypt, have been discovered. This lack of temples and statuary has resulted in the belief that the focus of religious life was primarily centered in the home. Anthropologists are relatively certain that the peoples of the Indus civilization emphasized ritual purity. Much of this is evidenced by the presence of drainable baths in most of the residences, as well as a great bath or pool surrounded by a pillared hall with small cell-like rooms. Scholars have surmised that washing and bathing were integral to the preservation of purity and that cleanliness was considered necessary to ward off evil spirits.
Similar to the culture of Egypt, it appears that the Indus religion recognized some type of life after death. Unlike later Indians, who practiced cremation, this civilization carefully buried their dead with their heads facing north and the feet pointing south. Included in the graves were pottery jars containing food and weapons for use in the afterlife.
Tuesday, December 2, 2008
An Overview of Ancient India.
Archaeological excavations have brought to light the remains of a highly developed urban civilisation in ancient India that stretched across approximately 1520 kilometres, extending from the area on the upper Sutlaj in contemporary Punjab to Lothal in Gujarat. Historians are of the view that this civilisation flourished in the third millennium before the birth of Christ.
It is known by the name of the two of its great cities - Harappa and Mohenjodaro situated on the left and the right bank respectively of the river Ravi in Punjab. The two cities were built on a similar plan - houses constructed with standard burnt bricks arranged in squares, along roads intersecting at right angles. The houses varied in size but were all based on the same plan - a small courtyard surrounded by rooms with entrances in side alleys, often multistoried with no windows opening out to the street. The houses had bathrooms and the drains flowing out were connected to covered sewers with soak-pits. This unique sewage system is amongst the most impressive achievements of the Indus people and sets them apart from all other ancient civilisations.
By about 1500 B.C. an important change began to occur in the northern half of the Indian sub-continent. The Harappa culture in the Indus Valley had declined by about 1750 B.C, and the stage was being set for a second and more continuous urbanisation in the Ganges Valley.
The earliest literary source that sheds light on India's past is the Rig Veda. It is difficult to date this work with any accuracy on the basis of tradition and ambiguous astronomical information contained in the hymns. It is most likely that Rig Veda was composed between 1,500 B.C. and 1,000 B.C.The people who composed these evocative hymns to nature and celebrated life exuberantly referred to themselves as Aryas usually anglicised as Aryan meaning 'superior'.
The 6th Century B.C. was a period of great ferment in India. The kingdom of Magadh -one of the 16 great janapadas - polities - had established paramountcy over other kingdoms of the Ganges Valley. This was the time when Buddhism and Jainism emerged as popular protestant movements to pose a serious challenge to Brahmanic orthodoxy. The fluid political situation, made it possible for Chandragupta Maurya (reign - 322 - 298 B.C.) to oust the oppressive ruler of Magadh and found his own dynasty.
The most famous of the Mauryas is Ashoka the Great (reign - 273 - 232 B.C.). He extended the boundaries of his empire considerably - stretching from Kashmir and Peshawar in the North and Northwest to Mysore in the South and Orissa in the East - but his fame rests not so much on military conquests as on his celebrated renunciation of war. After witnessing the carnage at the battle field of Kalinga (269 B.C.) in Orissa, Ashoka resolved to dedicate himself to Dhamma - or righteousness.
Ashoka died around 232 B.C. and the empire began to disintegrate under weak successors. Pushyamitra Shunga, a Brahmin general usurped the throne after slaying the last Maurya king and presided over a loosely federal polity. In subsequent centuries India suffered a series of invasions, and in the absence of a strong central authority, often fell under the spell of foreign rulers - Indo Bactrians, the Sakas and others.
For the next four hundred years, India remained politically disunited and weak. It was repeatedly raided and plundered by foreigners. Stability was restored by the Guptas. Exploits of Samudra Gupta (reign - 335 - 380 A.D.) - an illustrious ruler of this line - are recorded on a stone inscription at Allahabad.
It was Chandra Gupta II (reign - 380 - 412 A.D.) - Samudra Gupta's successor - who finally defeated the Sakas and re-established a strong central authority. His reign registered the high watermark in Indian culture. His accomplishments in war and peace were glorious enough for him to claim the title Vikramaditya - the resplendent, great and good king of legends. Fa-hien, a Chinese traveller who was in India from 399 - 414 A.D. has left an interesting account of contemporary India. This age of peace and prosperity witnessed an unprecedented flowering of art, literature and the sciences.
Kalidas, the famous Sanskrit poet and dramatist, author of Abhijnana Shankuntalam, Kumarsambhavam and Meghadutam is believed to have adorned the Gupta court. Mathematicians like Aryabhatta and astronomers like Varahmihir lived during this period. The dazzling wall paintings of Ajanta too are traced back to this era. This period also saw the beginning of Hindu temple architecture.
The twilight of the Gupta Empire saw the setting in of decay. Powerful feudal governors in the provinces declared their independence. Trade and commerce suffered and social evils crept in. There was only a brief afterglow in the time of Harshavardhan (reign - 604 - 647 A.D.) - of Kannauj - who is famous for his philanthrophy and patronage of Buddhism. Himself an accomplished writer, he encouraged eminent dramatists like Bana. A Chinese traveller Huen-tsang visited India from (629 - 645 A.D.) during the rule of Harshavardhan. His account gives us an opportunity to note the changes that had taken place in the lives of the Indian people since the days of the Guptas.
In the Deccan, the Cholas ruled over what today are the districts of Thanjavur and Tiruchirapally. In the 2nd Century B.C. a Chola prince conquered Sri Lanka. The Pandyas reigned around present day Tirunelvelli and Madurai. A Pandyan king sent an ambassador to the court of the Roman emperor Augustus in first Century B.C. The territory under the Cheras was what constitutes the present day central and northern Kerala.
Pallavas of Kanchi rose to prominence in the 4th Century A.D. and ruled unchallenged for about four hundred years. The Nayanar and Alvar saint poets belong to this period. The gemlike shore temples at Mahabalipuram date to this period.
The Cholas overthrew the Pallavas in the 9th Century and regained political primacy in south India. The exquisitely crafted Chola bronzes - the resplendent Natraja - the Dancing Shiva - have introduced the world to the glory of the Cholas. The tide of political fortunes turned once again in the 13th Century to make the Pandyas dominant. Their kingdom became a great centre of international trade. Art, literature and culture flourished under generous patronage. The 15th Century saw the decline of the Pandyas.
Foreign invasions had little impact on the life in southern India and this region remained unaffected by political upheavals that convulsed the north.
It is known by the name of the two of its great cities - Harappa and Mohenjodaro situated on the left and the right bank respectively of the river Ravi in Punjab. The two cities were built on a similar plan - houses constructed with standard burnt bricks arranged in squares, along roads intersecting at right angles. The houses varied in size but were all based on the same plan - a small courtyard surrounded by rooms with entrances in side alleys, often multistoried with no windows opening out to the street. The houses had bathrooms and the drains flowing out were connected to covered sewers with soak-pits. This unique sewage system is amongst the most impressive achievements of the Indus people and sets them apart from all other ancient civilisations.
By about 1500 B.C. an important change began to occur in the northern half of the Indian sub-continent. The Harappa culture in the Indus Valley had declined by about 1750 B.C, and the stage was being set for a second and more continuous urbanisation in the Ganges Valley.
The earliest literary source that sheds light on India's past is the Rig Veda. It is difficult to date this work with any accuracy on the basis of tradition and ambiguous astronomical information contained in the hymns. It is most likely that Rig Veda was composed between 1,500 B.C. and 1,000 B.C.The people who composed these evocative hymns to nature and celebrated life exuberantly referred to themselves as Aryas usually anglicised as Aryan meaning 'superior'.
The 6th Century B.C. was a period of great ferment in India. The kingdom of Magadh -one of the 16 great janapadas - polities - had established paramountcy over other kingdoms of the Ganges Valley. This was the time when Buddhism and Jainism emerged as popular protestant movements to pose a serious challenge to Brahmanic orthodoxy. The fluid political situation, made it possible for Chandragupta Maurya (reign - 322 - 298 B.C.) to oust the oppressive ruler of Magadh and found his own dynasty.
The most famous of the Mauryas is Ashoka the Great (reign - 273 - 232 B.C.). He extended the boundaries of his empire considerably - stretching from Kashmir and Peshawar in the North and Northwest to Mysore in the South and Orissa in the East - but his fame rests not so much on military conquests as on his celebrated renunciation of war. After witnessing the carnage at the battle field of Kalinga (269 B.C.) in Orissa, Ashoka resolved to dedicate himself to Dhamma - or righteousness.
Ashoka died around 232 B.C. and the empire began to disintegrate under weak successors. Pushyamitra Shunga, a Brahmin general usurped the throne after slaying the last Maurya king and presided over a loosely federal polity. In subsequent centuries India suffered a series of invasions, and in the absence of a strong central authority, often fell under the spell of foreign rulers - Indo Bactrians, the Sakas and others.
For the next four hundred years, India remained politically disunited and weak. It was repeatedly raided and plundered by foreigners. Stability was restored by the Guptas. Exploits of Samudra Gupta (reign - 335 - 380 A.D.) - an illustrious ruler of this line - are recorded on a stone inscription at Allahabad.
It was Chandra Gupta II (reign - 380 - 412 A.D.) - Samudra Gupta's successor - who finally defeated the Sakas and re-established a strong central authority. His reign registered the high watermark in Indian culture. His accomplishments in war and peace were glorious enough for him to claim the title Vikramaditya - the resplendent, great and good king of legends. Fa-hien, a Chinese traveller who was in India from 399 - 414 A.D. has left an interesting account of contemporary India. This age of peace and prosperity witnessed an unprecedented flowering of art, literature and the sciences.
Kalidas, the famous Sanskrit poet and dramatist, author of Abhijnana Shankuntalam, Kumarsambhavam and Meghadutam is believed to have adorned the Gupta court. Mathematicians like Aryabhatta and astronomers like Varahmihir lived during this period. The dazzling wall paintings of Ajanta too are traced back to this era. This period also saw the beginning of Hindu temple architecture.
The twilight of the Gupta Empire saw the setting in of decay. Powerful feudal governors in the provinces declared their independence. Trade and commerce suffered and social evils crept in. There was only a brief afterglow in the time of Harshavardhan (reign - 604 - 647 A.D.) - of Kannauj - who is famous for his philanthrophy and patronage of Buddhism. Himself an accomplished writer, he encouraged eminent dramatists like Bana. A Chinese traveller Huen-tsang visited India from (629 - 645 A.D.) during the rule of Harshavardhan. His account gives us an opportunity to note the changes that had taken place in the lives of the Indian people since the days of the Guptas.
In the Deccan, the Cholas ruled over what today are the districts of Thanjavur and Tiruchirapally. In the 2nd Century B.C. a Chola prince conquered Sri Lanka. The Pandyas reigned around present day Tirunelvelli and Madurai. A Pandyan king sent an ambassador to the court of the Roman emperor Augustus in first Century B.C. The territory under the Cheras was what constitutes the present day central and northern Kerala.
Pallavas of Kanchi rose to prominence in the 4th Century A.D. and ruled unchallenged for about four hundred years. The Nayanar and Alvar saint poets belong to this period. The gemlike shore temples at Mahabalipuram date to this period.
The Cholas overthrew the Pallavas in the 9th Century and regained political primacy in south India. The exquisitely crafted Chola bronzes - the resplendent Natraja - the Dancing Shiva - have introduced the world to the glory of the Cholas. The tide of political fortunes turned once again in the 13th Century to make the Pandyas dominant. Their kingdom became a great centre of international trade. Art, literature and culture flourished under generous patronage. The 15th Century saw the decline of the Pandyas.
Foreign invasions had little impact on the life in southern India and this region remained unaffected by political upheavals that convulsed the north.
Tuesday, November 25, 2008
Networking Questions with answers:Part-III
41. What is virtual channel?
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.
42. What is virtual path?
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.
43. What is packet filter?
Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.
44. What is traffic shaping?
One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping.
45. What is multicast routing?
Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing.
46. What is region?
When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions.
47. What is silly window syndrome?
It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time.
48. What are Digrams and Trigrams?
The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion.
49. Expand IDEA.
IDEA stands for International Data Encryption Algorithm.
50. What is wide-mouth frog?
Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol.
51. What is Mail Gateway?
It is a system that performs a protocol translation between different electronic mail delivery protocols.
52. What is IGP (Interior Gateway Protocol)?
It is any routing protocol used within an autonomous system.
53. What is EGP (Exterior Gateway Protocol)?
It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system.
54. What is autonomous system?
It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol.
55. What is BGP (Border Gateway Protocol)?
It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol).
56. What is Gateway-to-Gateway protocol?
It is a protocol formerly used to exchange routing information between Internet core routers.
57. What is NVT (Network Virtual Terminal)?
It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session.
58. What is a Multi-homed Host?
It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host.
59. What is Kerberos?
It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files.
60. What is OSPF?
It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions.
61. What is Proxy ARP?
It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.
62. What is SLIP (Serial Line Interface Protocol)?
It is a very simple protocol used for transmission of IP datagrams across a serial line.
63. What is RIP (Routing Information Protocol)?
It is a simple protocol used to exchange information between the routers.
64. What is source route?
It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.
The End!
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.
42. What is virtual path?
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.
43. What is packet filter?
Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.
44. What is traffic shaping?
One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping.
45. What is multicast routing?
Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing.
46. What is region?
When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions.
47. What is silly window syndrome?
It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time.
48. What are Digrams and Trigrams?
The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion.
49. Expand IDEA.
IDEA stands for International Data Encryption Algorithm.
50. What is wide-mouth frog?
Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol.
51. What is Mail Gateway?
It is a system that performs a protocol translation between different electronic mail delivery protocols.
52. What is IGP (Interior Gateway Protocol)?
It is any routing protocol used within an autonomous system.
53. What is EGP (Exterior Gateway Protocol)?
It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system.
54. What is autonomous system?
It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol.
55. What is BGP (Border Gateway Protocol)?
It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol).
56. What is Gateway-to-Gateway protocol?
It is a protocol formerly used to exchange routing information between Internet core routers.
57. What is NVT (Network Virtual Terminal)?
It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session.
58. What is a Multi-homed Host?
It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host.
59. What is Kerberos?
It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files.
60. What is OSPF?
It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions.
61. What is Proxy ARP?
It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.
62. What is SLIP (Serial Line Interface Protocol)?
It is a very simple protocol used for transmission of IP datagrams across a serial line.
63. What is RIP (Routing Information Protocol)?
It is a simple protocol used to exchange information between the routers.
64. What is source route?
It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.
The End!
Thursday, November 20, 2008
Networking Questions with answers:Part-II
21. What is Bandwidth?
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth.
22. What are the types of Transmission media?
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
a) Guided Media:
These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
b) Unguided Media:
This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.
23. What is Project 802?
It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN
protocols.
It consists of the following:
802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.
802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.
Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.
24. What is Protocol Data Unit?
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).
25. What are the different type of networking / internetworking devices?
Repeater:
Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges:
These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.
Routers:
They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.
26. What is ICMP?
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.
27. What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.
28. What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver.
The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.
29. What is the minimum and maximum length of the header in the TCP segment and IP datagram?
The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.
30. What is the range of addresses in the classes of internet addresses?
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 - 247.255.255.255
31. What is the difference between TFTP and FTP application layer protocols?
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.
The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.
32. What are major types of networks and explain?
Server-based network
Peer-to-peer network
Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources.
Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration
33. What are the important topologies for networks?
BUS topology:
In this each computer is directly connected to primary network cable in a single line.
Advantages:
Inexpensive, easy to install, simple to understand, easy to extend.
STAR topology:
In this all computers are connected using a central hub.
Advantages:
Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.
RING topology:
In this all computers are connected in loop.
Advantages:
All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it.
34. What is mesh network?
A network in which there are multiple network links between computers to provide multiple paths for data to travel.
35. What is difference between baseband and broadband transmission?
In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.
36. Explain 5-4-3 rule?
In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.
37. What MAU?
In token Ring , hub is called Multistation Access Unit(MAU).
38. What is the difference between routable and non- routable protocols?
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router
39. Why should you care about the OSI Reference Model?
It provides a framework for discussing network operations and design.
40. What is logical link control?
One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.
cont-
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth.
22. What are the types of Transmission media?
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
a) Guided Media:
These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
b) Unguided Media:
This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.
23. What is Project 802?
It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN
protocols.
It consists of the following:
802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.
802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.
Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.
24. What is Protocol Data Unit?
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).
25. What are the different type of networking / internetworking devices?
Repeater:
Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges:
These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.
Routers:
They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.
26. What is ICMP?
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.
27. What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.
28. What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver.
The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.
29. What is the minimum and maximum length of the header in the TCP segment and IP datagram?
The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.
30. What is the range of addresses in the classes of internet addresses?
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 - 247.255.255.255
31. What is the difference between TFTP and FTP application layer protocols?
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.
The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.
32. What are major types of networks and explain?
Server-based network
Peer-to-peer network
Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources.
Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration
33. What are the important topologies for networks?
BUS topology:
In this each computer is directly connected to primary network cable in a single line.
Advantages:
Inexpensive, easy to install, simple to understand, easy to extend.
STAR topology:
In this all computers are connected using a central hub.
Advantages:
Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.
RING topology:
In this all computers are connected in loop.
Advantages:
All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it.
34. What is mesh network?
A network in which there are multiple network links between computers to provide multiple paths for data to travel.
35. What is difference between baseband and broadband transmission?
In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.
36. Explain 5-4-3 rule?
In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.
37. What MAU?
In token Ring , hub is called Multistation Access Unit(MAU).
38. What is the difference between routable and non- routable protocols?
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router
39. Why should you care about the OSI Reference Model?
It provides a framework for discussing network operations and design.
40. What is logical link control?
One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.
cont-
Wednesday, November 12, 2008
Networking Questions with answers.Part-I
These are some of the widely asked networking questions that I gathered from the net.
1. What are the two types of transmission technology available?
(i) Broadcast and (ii) point-to-point
2. What is subnet?
A generic term for section of a large networks usually separated by a bridge or router.
3. Difference between the communication and transmission.
Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc.
Communication means the meaning full exchange of information between two communication media.
4. What are the possible ways of data exchange?
(i) Simplex (ii) Half-duplex (iii) Full-duplex.
5. What is SAP?
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.
6. What do you meant by "triple X" in Networks?
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X"
7. What is frame relay, in which layer it comes?
Frame relay is a packet switching technology. It will operate in the data link layer.
8. What is terminal emulation, in which layer it comes?
Telnet is also called as terminal emulation. It belongs to application layer.
9. What is Beaconing?
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
10. What is redirector?
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.
11. What is NETBIOS and NETBEUI?
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications.
NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets.
12. What is RAID?
A method for providing fault tolerance by using multiple hard disk drives.
13. What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.
14. What is Brouter?
Hybrid devices that combine the features of both bridges and routers.
15. What is cladding?
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.
16. What is point-to-point protocol
A communications protocol used to connect computers to remote networking services including Internet service providers.
17. How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats
18. What is attenuation?
The degeneration of a signal over distance on a network cable is called attenuation.
19. What is MAC address?
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.
20. Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.
baud rate = bit rate / N
where N is no-of-bits represented by each signal shift.
cont-
1. What are the two types of transmission technology available?
(i) Broadcast and (ii) point-to-point
2. What is subnet?
A generic term for section of a large networks usually separated by a bridge or router.
3. Difference between the communication and transmission.
Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc.
Communication means the meaning full exchange of information between two communication media.
4. What are the possible ways of data exchange?
(i) Simplex (ii) Half-duplex (iii) Full-duplex.
5. What is SAP?
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.
6. What do you meant by "triple X" in Networks?
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X"
7. What is frame relay, in which layer it comes?
Frame relay is a packet switching technology. It will operate in the data link layer.
8. What is terminal emulation, in which layer it comes?
Telnet is also called as terminal emulation. It belongs to application layer.
9. What is Beaconing?
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
10. What is redirector?
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.
11. What is NETBIOS and NETBEUI?
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications.
NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets.
12. What is RAID?
A method for providing fault tolerance by using multiple hard disk drives.
13. What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.
14. What is Brouter?
Hybrid devices that combine the features of both bridges and routers.
15. What is cladding?
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.
16. What is point-to-point protocol
A communications protocol used to connect computers to remote networking services including Internet service providers.
17. How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats
18. What is attenuation?
The degeneration of a signal over distance on a network cable is called attenuation.
19. What is MAC address?
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.
20. Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.
baud rate = bit rate / N
where N is no-of-bits represented by each signal shift.
cont-
Saturday, November 8, 2008
My day cont-part II The Thriller!
Uhh,cant believe you are still reading.Very well, go ahead, be my fan.
So where were we...yup at my workplace.
I hate this part of the day so bad.Makes me feel so exposed to the deadliest enemy ever-My professor!
I run for the lift ,but it was already on its way.I chase it down to the second floor,only to find that I'am already there at my destination.sigh
Second floor it is;the creepiest place of the electrical department of IIT.I sneak from behind the wall to get a glimpse of the end."High Voltage" it reads.Ye thats where I work, or lets assume I do.heh
The most jobless job I've ever been in, and I still remain undercover :P.Finding the corridor clear I pull off my earplugs,gather all the courage left inside and start walking towards the end,.chin down,hoping the devil doesnt catch me coming late red handed.
Phew that was close,I finally reach the end, but thats not just it.I have to cross the devils lair to reach my room-"My professors lobby".This is called living hell.
Do or die situation.The chances of my survival-1 outta 3.
1.I stay, I get caught when he comes out.
2.I walk past his lobby and he sees, I still get caught.
The punishment "where are the results??".And I would be made to sit and whine forever unless I showed him what he expects. God knows what the devil expects!
Man but I just love working here unless I get caught in his sight.heh
3.My only chance of survival!-To get to the other side unnoticed.
Hm..very bleak chance indeed.Just then this idea pops up in my mind.
I go to the other end of the lab where they store the components.Grab a big cylinder which looks like a fire extinguisher.Shit its heavy.I turn in over and it reads"14kOhm".
Never seen a resistor this big! Nevermind,when was the last time I handled one,heh,technology develops so rapidly I guess.
I held it in front and just hurried past the lobby.The professor did indeed see me and assumed that I was deeply involved in my work! Yipee.
Din lives to fight yet another day.lol
Everyone had arrived ahead of me.They always did.I could see cold stares piercing me,as I walked past each room,cursing me for having escaped yet again.I smirk back at them with an evil look and finally enter my room.
So where were we...yup at my workplace.
I hate this part of the day so bad.Makes me feel so exposed to the deadliest enemy ever-My professor!
I run for the lift ,but it was already on its way.I chase it down to the second floor,only to find that I'am already there at my destination.sigh
Second floor it is;the creepiest place of the electrical department of IIT.I sneak from behind the wall to get a glimpse of the end."High Voltage" it reads.Ye thats where I work, or lets assume I do.heh
The most jobless job I've ever been in, and I still remain undercover :P.Finding the corridor clear I pull off my earplugs,gather all the courage left inside and start walking towards the end,.chin down,hoping the devil doesnt catch me coming late red handed.
Phew that was close,I finally reach the end, but thats not just it.I have to cross the devils lair to reach my room-"My professors lobby".This is called living hell.
Do or die situation.The chances of my survival-1 outta 3.
1.I stay, I get caught when he comes out.
2.I walk past his lobby and he sees, I still get caught.
The punishment "where are the results??".And I would be made to sit and whine forever unless I showed him what he expects. God knows what the devil expects!
Man but I just love working here unless I get caught in his sight.heh
3.My only chance of survival!-To get to the other side unnoticed.
Hm..very bleak chance indeed.Just then this idea pops up in my mind.
I go to the other end of the lab where they store the components.Grab a big cylinder which looks like a fire extinguisher.Shit its heavy.I turn in over and it reads"14kOhm".
Never seen a resistor this big! Nevermind,when was the last time I handled one,heh,technology develops so rapidly I guess.
I held it in front and just hurried past the lobby.The professor did indeed see me and assumed that I was deeply involved in my work! Yipee.
Din lives to fight yet another day.lol
Everyone had arrived ahead of me.They always did.I could see cold stares piercing me,as I walked past each room,cursing me for having escaped yet again.I smirk back at them with an evil look and finally enter my room.
Sunday, November 2, 2008
INTERVIEW QUESTIONS & ANSWERS FROM C, C ++ part-VI
What is the handle class?
A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.
Explanation:In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object’s state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references
What is a protocol class?
An abstract class is a protocol class if:-
It neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.It has a non-inline virtual destructor defined with an empty implementation,all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.
What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.
Define precondition and post-condition to a member function.
Precondition:-A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.
Post-condition:-A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.
What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.
Differentiate between the message and method.
Message:- Objects communicate by sending messagesto each other.A message is sent to invoke a method.
Method:- Provides response to a message.It is an implementation of an operation.
What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over.
This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.
When does a name clash occur?
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.
Differentiate between a template class and class template?
Template class:-A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
Class template:-A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.
What problem does the namespace feature solve?
Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of course.
What is the Standard Template Library?
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.
What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.
What is a mutable member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.
Understanding this requirement implies an understanding of C++ const, which many programmers do not have. I have seen large class designs that do not employ the const qualifier anywhere. Some of those designs are my own early C++ efforts. One author suggests that some programmers find const to be such a bother that it is easier to ignore const than to try to use it meaningfully. No wonder many programmers don’t understand the power and implications of const. Someone who claims to have enough interest in the language and its evolution to keep pace with the ANSI deliberations should not be ignorant of const, however.
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.
Prior to templates, you had to use inheritance; your design might include a generic List container class and an application-specific Employee class. To put employees in a list, a ListedEmployee class is multiply derived (contrived) from the Employee and List classes. These solutions were unwieldy and error-prone. Templates solved that problem.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class “is” a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee “has” a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.
The answer to this question reveals whether the applicant has an understanding of the fundamentals of object- oriented design, which is important to reliable class design.
There are other relationships. The USESA relationship is when one class uses the services of another. The Employee class uses an object (cout) of the ostream class to display the employee’s name on the screen, for example. But if the applicant gets ISA and HASA right, you don’t need to go any further.
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete.
When should you use multiple inheritance?
There are three acceptable answers: “Never,” “Rarely,” and “When the problem domain cannot be accurately modeled any other way.” There are some famous C++ pundits and luminaries who disagree with that third answer, but I will accept it.
Let’s digress to consider this issue lest your interview turn into a religious debate. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
First, the applicant must know that a copy constructor is one that has only one argument of the same type as the constructor. The compiler invokes a copy constructor wherever it needs to make a copy of the object, for example to pass an argument by value. If you do not provide a copy constructor, the compiler creates a member- by-member copy constructor for you.
You can write overloaded assignment operators that take arguments of other classes, but that behavior is usually implemented with implicit conversion constructors. If you do not provide an overloaded assignment operator for the class, the compiler creates a default member- by-member assignment operator.
This discussion is a good place to get into why classes need copy constructors and overloaded assignment operators. If the applicant discusses these with respect to data member pointers that point to dynamically allocated resources, the applicant probably has a good grasp of the problem.
What is a conversion constructor?
A constructor that accepts one argument of a different type.
The compiler uses this idiom as one way to infer conversion rules for your class. A constructor with more than one argument and with default argument values can be interpreted by the compiler as a conversion constructor when the compiler is looking for an object of your constructor’s type and sees an object of the type of the constructor’s first argument.
What is a default constructor?
A constructor that has no arguments.
If you don’t code one, the compiler provides one if there are no other constructors. If you are going to instantiate an array of objects of the class, the class must have a default constructor.
What is your reaction to this line of code?
It’s not a good practice.
Many applicants will look at you like you are nuts. They’ve never heard of this usage, and it’s never occurred to them. That’s a very good answer. Perhaps they will try to explain the behavior of the statement. Ask them to contemplate its consequences. Two quite acceptable reactions are, “Don’t do it,” and “Don’t do it unless you really know what you are doing and you are a masochist.”
A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that’s another matter. In More Effective C++ (Addison-Wesley, 1996), Scott Meyers devotes one of his items to “delete this,” implying that there are valid applications for the idiom and advancing contrived code kludges to make it seem to work better. A programmer who has read this otherwise very good book might think that the practice is acceptable. Experience leads me to disagree.
How does throwing and catching exceptions differ from using setjmp and longjmp?
The throw operation calls the destructors for automatic objects instantiated since entry to the try block.
Exceptions are in the mainstream of C++ now, so most programmers, if they are familiar with setjmp and longjmp, should know the difference. Both idioms return a program from the nested depths of multiple function calls to a defined position higher in the program. The program stack is “unwound” so that the state of the program, with respect to function calls and pushed arguments, is restored as if the calls had not been made. C++ exception handling adds to that behavior the orderly calls to the destructors of automatic objects that were instantiated as the program proceeded from within the try block toward where the throw expression is evaluated.
Applicants might think you want to hear about the notational differences between the two idioms. Let them proceed to explain the syntax of try blocks, catch exception handlers, and throw expressions. Then ask them specifically what happens in a throw that does not happen in a longjmp.
One valid reason for not knowing about exception handling is that the applicant’s experience is exclusively with older C++ compilers that do not implement exception handling. I would prefer that they have at least heard of exception handling, though. Another marginally acceptable reason is that their former supervisors and designers did not mandate and specify the use of exception handling in programs. In that case get the names of those supervisors and designers so that you can decline their applications if they should come a’knocking.
It is not unusual for C and C++ programmers to be unfamiliar with setjmp/
longjmp. Those constructs are not particularly intuitive. A C programmer who has written recursive descent parsing algorithms will certainly be familiar with setjmp/longjmp. Others might not, and that’s acceptable. In that case, they won’t be able to discuss how setjmp/longjmp differs from C++ exception handling, but let the interview turn into a discussion of C++ exception handling in general. That conversation will reveal a lot about a programmer’s understanding of C++.
How many ways are there to initialize an int with a constant?
There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);
It’s acceptable when a programmer does not know about the second notation, although they should certainly know about the first one. Many old-timer C programmers who made the switch to C++ never use the second idiom, although some wise heads of C++ profess to prefer it. If your applicant is quick with the right answer, that’s a good sign.
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifiers are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifiers, member functions, overloaded operators, and so on. Some of them have even written books about C++. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specifier and private base-class inheritance. Getting this question wrong does not necessarily disqualify an applicant. Getting it right is a definite plus.
Saying, “I don’t know” is definitely the wrong answer. I advance an unusual position about this. C++ programmers should at least believe that they know the differences, even when they are wrong about them. Getting it wrong is, therefore, right. You can explain the true difference in the interview and advance the programmer’s knowledge. If they disagree vociferously, you have an opportunity to observe how they handle contentious debate when they are wrong and don’t know it yet.
Explain the scope resolution operator.
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
The answer can get complicated. However, it should start with “::”. If the programmer is well into the design or use of classes that employ inheritance you might hear a lot about overriding member function overrides to explicitly call a function higher in the hierarchy. That’s good to know, but ask specifically about global scope resolution. You’re looking for a description of C++’s ability to override the particular C behavior where identifiers in the global scope are always hidden by like identifiers in a local scope.
How do you link a C++ program to C functions?
By using the extern “C” linkage specification around the C function declarations.
Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern “C” linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
Another acceptable answer is “I don’t know. We never had to do that.” Merely describing what a linker does indicates that the programmer does not understand the issue that underlies the question.
Hope it helped!
A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.
Explanation:In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object’s state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references
What is a protocol class?
An abstract class is a protocol class if:-
It neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.It has a non-inline virtual destructor defined with an empty implementation,all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.
What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.
Define precondition and post-condition to a member function.
Precondition:-A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.
Post-condition:-A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.
What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.
Differentiate between the message and method.
Message:- Objects communicate by sending messagesto each other.A message is sent to invoke a method.
Method:- Provides response to a message.It is an implementation of an operation.
What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over.
This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.
When does a name clash occur?
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.
Differentiate between a template class and class template?
Template class:-A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
Class template:-A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.
What problem does the namespace feature solve?
Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of course.
What is the Standard Template Library?
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.
What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It’s purpose is reserved explicitly for construction.
What is a mutable member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.
Understanding this requirement implies an understanding of C++ const, which many programmers do not have. I have seen large class designs that do not employ the const qualifier anywhere. Some of those designs are my own early C++ efforts. One author suggests that some programmers find const to be such a bother that it is easier to ignore const than to try to use it meaningfully. No wonder many programmers don’t understand the power and implications of const. Someone who claims to have enough interest in the language and its evolution to keep pace with the ANSI deliberations should not be ignorant of const, however.
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.
Prior to templates, you had to use inheritance; your design might include a generic List container class and an application-specific Employee class. To put employees in a list, a ListedEmployee class is multiply derived (contrived) from the Employee and List classes. These solutions were unwieldy and error-prone. Templates solved that problem.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class “is” a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee “has” a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.
The answer to this question reveals whether the applicant has an understanding of the fundamentals of object- oriented design, which is important to reliable class design.
There are other relationships. The USESA relationship is when one class uses the services of another. The Employee class uses an object (cout) of the ostream class to display the employee’s name on the screen, for example. But if the applicant gets ISA and HASA right, you don’t need to go any further.
What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete.
When should you use multiple inheritance?
There are three acceptable answers: “Never,” “Rarely,” and “When the problem domain cannot be accurately modeled any other way.” There are some famous C++ pundits and luminaries who disagree with that third answer, but I will accept it.
Let’s digress to consider this issue lest your interview turn into a religious debate. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
First, the applicant must know that a copy constructor is one that has only one argument of the same type as the constructor. The compiler invokes a copy constructor wherever it needs to make a copy of the object, for example to pass an argument by value. If you do not provide a copy constructor, the compiler creates a member- by-member copy constructor for you.
You can write overloaded assignment operators that take arguments of other classes, but that behavior is usually implemented with implicit conversion constructors. If you do not provide an overloaded assignment operator for the class, the compiler creates a default member- by-member assignment operator.
This discussion is a good place to get into why classes need copy constructors and overloaded assignment operators. If the applicant discusses these with respect to data member pointers that point to dynamically allocated resources, the applicant probably has a good grasp of the problem.
What is a conversion constructor?
A constructor that accepts one argument of a different type.
The compiler uses this idiom as one way to infer conversion rules for your class. A constructor with more than one argument and with default argument values can be interpreted by the compiler as a conversion constructor when the compiler is looking for an object of your constructor’s type and sees an object of the type of the constructor’s first argument.
What is a default constructor?
A constructor that has no arguments.
If you don’t code one, the compiler provides one if there are no other constructors. If you are going to instantiate an array of objects of the class, the class must have a default constructor.
What is your reaction to this line of code?
It’s not a good practice.
Many applicants will look at you like you are nuts. They’ve never heard of this usage, and it’s never occurred to them. That’s a very good answer. Perhaps they will try to explain the behavior of the statement. Ask them to contemplate its consequences. Two quite acceptable reactions are, “Don’t do it,” and “Don’t do it unless you really know what you are doing and you are a masochist.”
A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that’s another matter. In More Effective C++ (Addison-Wesley, 1996), Scott Meyers devotes one of his items to “delete this,” implying that there are valid applications for the idiom and advancing contrived code kludges to make it seem to work better. A programmer who has read this otherwise very good book might think that the practice is acceptable. Experience leads me to disagree.
How does throwing and catching exceptions differ from using setjmp and longjmp?
The throw operation calls the destructors for automatic objects instantiated since entry to the try block.
Exceptions are in the mainstream of C++ now, so most programmers, if they are familiar with setjmp and longjmp, should know the difference. Both idioms return a program from the nested depths of multiple function calls to a defined position higher in the program. The program stack is “unwound” so that the state of the program, with respect to function calls and pushed arguments, is restored as if the calls had not been made. C++ exception handling adds to that behavior the orderly calls to the destructors of automatic objects that were instantiated as the program proceeded from within the try block toward where the throw expression is evaluated.
Applicants might think you want to hear about the notational differences between the two idioms. Let them proceed to explain the syntax of try blocks, catch exception handlers, and throw expressions. Then ask them specifically what happens in a throw that does not happen in a longjmp.
One valid reason for not knowing about exception handling is that the applicant’s experience is exclusively with older C++ compilers that do not implement exception handling. I would prefer that they have at least heard of exception handling, though. Another marginally acceptable reason is that their former supervisors and designers did not mandate and specify the use of exception handling in programs. In that case get the names of those supervisors and designers so that you can decline their applications if they should come a’knocking.
It is not unusual for C and C++ programmers to be unfamiliar with setjmp/
longjmp. Those constructs are not particularly intuitive. A C programmer who has written recursive descent parsing algorithms will certainly be familiar with setjmp/longjmp. Others might not, and that’s acceptable. In that case, they won’t be able to discuss how setjmp/longjmp differs from C++ exception handling, but let the interview turn into a discussion of C++ exception handling in general. That conversation will reveal a lot about a programmer’s understanding of C++.
How many ways are there to initialize an int with a constant?
There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);
It’s acceptable when a programmer does not know about the second notation, although they should certainly know about the first one. Many old-timer C programmers who made the switch to C++ never use the second idiom, although some wise heads of C++ profess to prefer it. If your applicant is quick with the right answer, that’s a good sign.
What are the differences between a C++ struct and C++ class?
The default member and base-class access specifiers are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifiers, member functions, overloaded operators, and so on. Some of them have even written books about C++. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specifier and private base-class inheritance. Getting this question wrong does not necessarily disqualify an applicant. Getting it right is a definite plus.
Saying, “I don’t know” is definitely the wrong answer. I advance an unusual position about this. C++ programmers should at least believe that they know the differences, even when they are wrong about them. Getting it wrong is, therefore, right. You can explain the true difference in the interview and advance the programmer’s knowledge. If they disagree vociferously, you have an opportunity to observe how they handle contentious debate when they are wrong and don’t know it yet.
Explain the scope resolution operator.
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
The answer can get complicated. However, it should start with “::”. If the programmer is well into the design or use of classes that employ inheritance you might hear a lot about overriding member function overrides to explicitly call a function higher in the hierarchy. That’s good to know, but ask specifically about global scope resolution. You’re looking for a description of C++’s ability to override the particular C behavior where identifiers in the global scope are always hidden by like identifiers in a local scope.
How do you link a C++ program to C functions?
By using the extern “C” linkage specification around the C function declarations.
Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern “C” linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
Another acceptable answer is “I don’t know. We never had to do that.” Merely describing what a linker does indicates that the programmer does not understand the issue that underlies the question.
Hope it helped!
Saturday, October 25, 2008
INTERVIEW QUESTIONS & ANSWERS FROM C, C ++ part-V
How do I write code that reads data at memory location specified by segment and offset?
Use peekb( ) function. This function returns byte(s) read from specific segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function.
#include
#include
main( )
{
char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;
if ( ( fp = fopen ( “scr.dat”, “wb” ) ) == NULL )
{
printf ( “\nUnable to open file” ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ ) fprintf ( fp, “%c”, peekb ( scr, offset ) ) ; fclose ( fp ) ; if ( ( fp = fopen ( “scr.dat”, “rb” ) ) == NULL ) { printf ( “\nUnable to open file” ) ; exit( ) ; } // reads and writes to file for ( offset = 0 ; offset < 160 ; offset++ ) { fscanf ( fp, “%c”, &ch ) ; printf ( “%c”, ch ) ; } fclose ( fp ) ; }
How do I write code to find an amount of free disk space available on current drive?
Use getdfree( ) function as shown in follow code.
#include
#include
#include
#include
main( )
{
int dr ; struct dfree disk ;
long freesp ;
dr = getdisk( ) ;
getdfree ( dr + 1 , &disk ) ;
if ( disk.df_sclus == 0xFFFF )
{
printf ( “\ngetdfree( ) function failed\n”);
exit ( 1 ) ;
}
freesp = ( long ) disk.df_avail
* ( long ) disk.df_bsec
* ( long ) disk.df_sclus ;
printf ( “\nThe current drive %c: has %ld bytes
available as free space\n”, ‘A’ + dr, freesp ) ;
}
The functions memcmp( ) and memicmp( )
#include
#include
main( )
{
char str1[] = “This string contains some
characters” ;
char str2[] = “this string contains” ;
int result ;
result = memcmp ( str1, str2, strlen ( str2 ) ) ;
printf ( “\nResult after comapring buffer using
memcmp( )” ) ;
show ( result ) ;
result = memicmp ( str1, str2, strlen ( str2 ) ) ;
printf ( “\nResult after comapring buffer using
memicmp( )” ) ;
show ( result ) ;
}
show ( int r )
{
if ( r == 0 )
printf ( “\nThe buffer str1 and str2 hold
identical data” ) ;
if ( r > 0 )
printf ( “\nThe buffer str1 is bigger than buffer
str2″ ) ;
if ( r < 0 ) printf ( “\nThe buffer str1 is less than buffer str2″ ) ; }
How do I write code to get the current drive as well as set the current drive?
The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates ‘A’ as the current drive, 1 as ‘B’ and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.
#include
main( )
{
int dno, maxdr ;
dno = getdisk( ) ;
printf ( “\nThe current drive is: %c\n”, 65 + dno
) ;
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( “\nNow the current drive is: %c\n”, 65 +
dno ) ;
}
How do I write code that would get error number and display error message if any standard error occurs?
Following code demonstrates this.
#include
#include
#include
main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( “C:\file.txt”, “r” ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( “\n%s”, errmsg ) ;
}
}
Here, we are trying to open ‘file.txt’ file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in ’stdlib.h’ and also in ‘errno.h’. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.
How do I change the type of cursor and hide a cursor?
We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor.
#include
main( )
{
/* Hide cursor */
_setcursortype ( _NOCURSOR ) ;
/* Change cursor to a solid cursor */
_setcursortype ( _SOLIDCURSOR ) ;
/* Change back to the normal cursor */
_setcursortype ( _NORMALCURSOR ) ;
}
How do I write code to retrieve current date and time from the system and display it as a string?
Use time( ) function to get current date and time and then ctime( ) function to display it as a string. This is shown in following code snippet.
#include
void main( )
{
time_t curtime ;
char ctm[50] ;
time ( &curtime ) ; //retrieves current time &
stores in curtime
printf ( “\nCurrent Date & Time: %s”, ctime (
&curtime ) ) ;
}
How do I know how many elements an array can hold?
The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model.
main( )
{
int i[32767] ;
float f[16383] ;
char s[65535] ;
}
Why doesn’t the following statement work?
char str[ ] = “Hello” ;
strcat ( str, ‘!’ ) ;
Ans: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:
strcat ( str, “!” ) ;
Why doesn’t the following code give the desired result?
int x = 3000, y = 2000 ;
long int z = x * y ;
Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:
long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect
What will be the output of the following code?
void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d”,a[i]) ;
}
Ans: The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.
What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation
What do you mean by Stack unwinding?
It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.
What is a mixin class?
A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don’t share common bases.
What is a concrete class?
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.
What is cloning?
An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.
What is an opaque pointer?
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.
What sorting algos have their best and worst case times equal ?
O(nlogn) for mergesort and heap sort
What is an abstract class?
A class which cannot be Instantiated.
Static binding occurs at Compile Time,Runtime?
Both at compile and runtime.
What will a read() function do?.
A method in Input Stream.It reads a single byte or an array of bytes.Returns no of bytes read or -1 if EOF(End of file)is reached
Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
What is a smart pointer?
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don’t respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Will the inline function be compiled as the inline function always? Justify.
An inline function is a request and not a command. Hence it won’t be compiled as an inline function always.
Explanation:Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.
What is reflexive association?
The ‘is-a’ is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a ’specializes-from’ as ’specializes-from’ is usually used to describe the association between a super-class and a sub-class.
For example:Printer is-a printer.
Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable
What is a parameterized type?
A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.
Use peekb( ) function. This function returns byte(s) read from specific segment and offset locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function.
#include
#include
main( )
{
char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;
if ( ( fp = fopen ( “scr.dat”, “wb” ) ) == NULL )
{
printf ( “\nUnable to open file” ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ ) fprintf ( fp, “%c”, peekb ( scr, offset ) ) ; fclose ( fp ) ; if ( ( fp = fopen ( “scr.dat”, “rb” ) ) == NULL ) { printf ( “\nUnable to open file” ) ; exit( ) ; } // reads and writes to file for ( offset = 0 ; offset < 160 ; offset++ ) { fscanf ( fp, “%c”, &ch ) ; printf ( “%c”, ch ) ; } fclose ( fp ) ; }
How do I write code to find an amount of free disk space available on current drive?
Use getdfree( ) function as shown in follow code.
#include
#include
#include
#include
main( )
{
int dr ; struct dfree disk ;
long freesp ;
dr = getdisk( ) ;
getdfree ( dr + 1 , &disk ) ;
if ( disk.df_sclus == 0xFFFF )
{
printf ( “\ngetdfree( ) function failed\n”);
exit ( 1 ) ;
}
freesp = ( long ) disk.df_avail
* ( long ) disk.df_bsec
* ( long ) disk.df_sclus ;
printf ( “\nThe current drive %c: has %ld bytes
available as free space\n”, ‘A’ + dr, freesp ) ;
}
The functions memcmp( ) and memicmp( )
#include
#include
main( )
{
char str1[] = “This string contains some
characters” ;
char str2[] = “this string contains” ;
int result ;
result = memcmp ( str1, str2, strlen ( str2 ) ) ;
printf ( “\nResult after comapring buffer using
memcmp( )” ) ;
show ( result ) ;
result = memicmp ( str1, str2, strlen ( str2 ) ) ;
printf ( “\nResult after comapring buffer using
memicmp( )” ) ;
show ( result ) ;
}
show ( int r )
{
if ( r == 0 )
printf ( “\nThe buffer str1 and str2 hold
identical data” ) ;
if ( r > 0 )
printf ( “\nThe buffer str1 is bigger than buffer
str2″ ) ;
if ( r < 0 ) printf ( “\nThe buffer str1 is less than buffer str2″ ) ; }
How do I write code to get the current drive as well as set the current drive?
The function getdisk( ) returns the drive number of current drive. The drive number 0 indicates ‘A’ as the current drive, 1 as ‘B’ and so on. The Setdisk( ) function sets the current drive. This function takes one argument which is an integer indicating the drive to be set. Following program demonstrates use of both the functions.
#include
main( )
{
int dno, maxdr ;
dno = getdisk( ) ;
printf ( “\nThe current drive is: %c\n”, 65 + dno
) ;
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( “\nNow the current drive is: %c\n”, 65 +
dno ) ;
}
How do I write code that would get error number and display error message if any standard error occurs?
Following code demonstrates this.
#include
#include
#include
main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( “C:\file.txt”, “r” ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( “\n%s”, errmsg ) ;
}
}
Here, we are trying to open ‘file.txt’ file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in ’stdlib.h’ and also in ‘errno.h’. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.
How do I change the type of cursor and hide a cursor?
We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor.
#include
main( )
{
/* Hide cursor */
_setcursortype ( _NOCURSOR ) ;
/* Change cursor to a solid cursor */
_setcursortype ( _SOLIDCURSOR ) ;
/* Change back to the normal cursor */
_setcursortype ( _NORMALCURSOR ) ;
}
How do I write code to retrieve current date and time from the system and display it as a string?
Use time( ) function to get current date and time and then ctime( ) function to display it as a string. This is shown in following code snippet.
#include
void main( )
{
time_t curtime ;
char ctm[50] ;
time ( &curtime ) ; //retrieves current time &
stores in curtime
printf ( “\nCurrent Date & Time: %s”, ctime (
&curtime ) ) ;
}
How do I know how many elements an array can hold?
The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an array cannot consume more than 64 kb. Consider following program, which shows the maximum number of elements an array of type int, float and char can have in case of Small memory model.
main( )
{
int i[32767] ;
float f[16383] ;
char s[65535] ;
}
Why doesn’t the following statement work?
char str[ ] = “Hello” ;
strcat ( str, ‘!’ ) ;
Ans: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:
strcat ( str, “!” ) ;
Why doesn’t the following code give the desired result?
int x = 3000, y = 2000 ;
long int z = x * y ;
Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:
long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect
What will be the output of the following code?
void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d”,a[i]) ;
}
Ans: The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.
What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation
What do you mean by Stack unwinding?
It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.
What is a mixin class?
A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don’t share common bases.
What is a concrete class?
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.
What is cloning?
An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.
What is an opaque pointer?
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.
What sorting algos have their best and worst case times equal ?
O(nlogn) for mergesort and heap sort
What is an abstract class?
A class which cannot be Instantiated.
Static binding occurs at Compile Time,Runtime?
Both at compile and runtime.
What will a read() function do?.
A method in Input Stream.It reads a single byte or an array of bytes.Returns no of bytes read or -1 if EOF(End of file)is reached
Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
What is a smart pointer?
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don’t respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Will the inline function be compiled as the inline function always? Justify.
An inline function is a request and not a command. Hence it won’t be compiled as an inline function always.
Explanation:Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.
What is reflexive association?
The ‘is-a’ is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a ’specializes-from’ as ’specializes-from’ is usually used to describe the association between a super-class and a sub-class.
For example:Printer is-a printer.
Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable
What is a parameterized type?
A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.
Monday, October 20, 2008
INTERVIEW QUESTIONS & ANSWERS FROM C, C ++ part-IV
What is garbage collection?
Suppose some memory space becomes reusable because a node is released from a linked list. Hence, we want the space to be available for future use. One way to bring this about is to immediately reinsert the space into the free-storage list. However, this method may be too time-consuming for the operating system. The operating system may periodically collect all the deleted space onto the free-storage list. The technique that does this collection is called Garbage Collection. Garbage Collection usually takes place in two steps: First the Garbage Collector runs through all lists, tagging whose cells are currently in use, and then it runs through the memory, collecting all untagged space onto the free-storage list. The Garbage Collection may take place when there is only some minimum amount of space or no space at all left in the free-storage list, or when the CPU is idle and has time to do the collection. Generally speaking, the Garbage Collection is invisible to the programmer..
Can we get the remainder of a floating point division ?
Yes. Although the % operator fails to work on float numbers we can still get the remainder of floating point division by using a function fmod( ). The fmod( ) function divides the two float numbers passed to it as parameters and returns the remainder as a floating-point value. Following program shows fmod( ) function at work.
#include
main( )
{
printf ( “%f”, fmod ( 5.15, 3.0 ) ) ;
}
The above code snippet would give the output as 2.150000.
What does the error “Null Pointer Assignment” mean and what causes this error?
The Null Pointer Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of the data segment. In Borland’s C or C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice “Borland C++ - Copyright 1991 Borland Intl.”. In the small and medium memory models, a null pointer points to DS:0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment.
What’s the difference between a null pointer, a NULL macro, the ASCII NUL character and a null string?
A null pointer is a pointer which doesn’t point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn’t have any relationship with the null pointer. The null string is just another name for an empty string “”.
What is the difference between const char *p, char const *p, and char* const p ?
‘const char *p’ and ‘char const *p’ are the same, i.e. p points to a constant character. On the other hand, ‘char* const p’ means p is a constant pointer pointing to a character which means we cannot change the pointer p but we can change the character which p is pointing to.
How to get the memory size ?
Consider the following program
#include
#include
main( )
{
int memsize;
memsize = biosmemory( ) ;
printf ( “RAM size = %dK\n”,memsize ) ;
return 0 ;
}
The function biosmemory uses BIOS interrupt 0×12 to return the size of memory.
How to use function strdup( ) in a program?
The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmer’s responsibility to deallocate the memory using free( ).
#include
#include
#include
void main( )
{
char *str1, *str2 = “double”;
str1 = strdup ( str2 ) ;
printf ( “%s\n”, str1 ) ;
free ( str1 ) ;
}
Can we change the system date to some other date?
Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function.
#include
#include
void main( )
{
time_t tm ;
int d ;
tm = time ( NULL ) ;
printf ( “The System Date : %s”, ctime ( &tm ) ) ;
printf ( “\nHow many days ahead you want to set the date : ” ) ;
scanf ( “%d”, &d ) ;
tm += ( 24L * d ) * 60L * 60L ;
stime ( &tm ) ;
printf ( “\nNow the new date is : %s”, ctime ( &tm ) ) ;
}
In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time
How do I write a function that takes variable number of arguments?
The following program demonstrates this.
#include
#include
void main( )
{
int i = 10 ;
float f = 2.5 ;
char *str = “Hello!” ;
vfpf ( “%d %f %s\n”, i, f, str ) ;
vfpf ( “%s %s”, str, “Hi!” ) ;
}
void vfpf ( char *fmt, … )
{
va_list argptr ;
va_start ( argptr, fmt ) ;
vfprintf ( stdout, fmt, argptr ) ;
va_end ( argptr ) ;
}
Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return.
Can we get the process identification number of the current program?
Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro.
#include
#include
void main( )
{
printf ( “The process identification number of this program is %X\n”,
getpid( ) ) ;
}
How to obtain a path of the given file?
The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function.
#include “dir.h”
void main ( int argc, char *argv[] )
{
char *path ;
if ( path = searchpath ( argv[ 1 ] ) )
printf ( “Pathname : %s\n”, path ) ;
else
printf ( “File not found\n” ) ;
}
Can we get the x and y coordinate of the current cursor position ?
The function wherex( ) and wherey( ) returns the x-coordinate and y-coordinate of the current cursor position respectively. Both the functions return an integer value. The value returned by wherex( ) is the horizontal position of cursor and the value returned by wherey( ) is the vertical position of the cursor. Following program shows how to use the wherex( ) and wherey( ) functions.
#include
main( )
{
printf ( “Just\n To\n Test\n Where\n the cursor\n goes” ) ;
printf ( “Current location is X: %d Y: %d\n”, wherex( ), wherey( ) ) ;
}
How to obtain the current drive through C ?
We can use the function _getdrive( ) to obtain the current drive. The _getdrive( ) function uses DOS function 0X19 to get the current drive number
#include
main( )
{
int disk ;
disk = _getdrive( ) + ‘A’ - 1 ;
printf ( “The current drive is: %c\n”, disk ) ;
}
How to restrict the program’s output to a specific screen region?
A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string ‘Hello!’ gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window.
#include
main( )
{
int i, j ;
window ( 20, 8, 60, 17 ) ;
for ( i = 0 ; i < j =" 0">
How do I print the contents of environment variables?
The following program shows how to achieve this:
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( “\n%s”, env[ i++ ] ) ;
}
main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables.
What’s the difference between these two declarations?
struct str1 { … } ;
typedef struct { … } str2 ;
Ans : The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type — its users don’t necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.
How do I convert a floating-point number to a string?
Use function gcvt( ) to convert a floating-point number to a string. Following program demonstrates the use of this function.
#include
main( )
{
char str[25] ;
float no ;
int dg = 5 ; /* significant digits */
no = 14.3216 ;
gcvt ( no, dg, str ) ;
printf ( “String: %s\n”, str ) ;
}
How to find the row and column dimension of a given 2-D array?
Whenever we initialize a 2-D array at the same place where it has been declared, it is not necessary to mention the row dimension of an array. The row and column dimensions of such an array can be determined programmatically as shown in following program.
void main( )
{
int a[][3] = { 0, 1, 2,
9,-6, 8,
7, 5, 44,
23, 11,15 } ;
int c = sizeof ( a[0] ) / sizeof ( int ) ;
int r = ( sizeof ( a ) / sizeof ( int ) ) / c ;
int i, j ;
printf ( “\nRow: %d\nCol: %d\n”, r, c ) ;
for ( i = 0 ; i < j =" 0">
How do I write printf( ) so that the width of a field can be specified at runtime?
This is shown in following code snippet.
main( )
{
int w, no ;
printf ( “Enter number and the width for the
number field:” ) ;
scanf ( “%d%d”, &no, &w ) ;
printf ( “%*d”, w, no ) ;
}
Here, an ‘*’ in the format specifier in printf( ) indicates that an int value from the argument list should be used for the field width.
Are the following two statements identical?
char str[6] = “Kicit” ;
char *str = “Kicit” ;
Ans: No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known
by name str. In other words there is a location named str at which six characters are stored. The pointer declaration char *str ; on the other hand, requests a place that holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any contiguous array of chars, or nowhere.
How do I compare character data stored at two different memory locations?
Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.
#include
main( )
{
char *arr1 = “Kicit” ;
char *arr2 = “kicitNagpur” ;
int c ;
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( “\nStrings arr1 and arr2 compared using memcmp are identical” ) ;
else
printf ( “\nStrings arr1 and arr2 compared using memcmp are not identical”
) ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( “\nStrings arr1 and arr2 compared using memicmp are identical” )
;
else
printf ( “\nStrings arr1 and arr2 compared using memicmp are not
identical” ) ;
}
Suppose some memory space becomes reusable because a node is released from a linked list. Hence, we want the space to be available for future use. One way to bring this about is to immediately reinsert the space into the free-storage list. However, this method may be too time-consuming for the operating system. The operating system may periodically collect all the deleted space onto the free-storage list. The technique that does this collection is called Garbage Collection. Garbage Collection usually takes place in two steps: First the Garbage Collector runs through all lists, tagging whose cells are currently in use, and then it runs through the memory, collecting all untagged space onto the free-storage list. The Garbage Collection may take place when there is only some minimum amount of space or no space at all left in the free-storage list, or when the CPU is idle and has time to do the collection. Generally speaking, the Garbage Collection is invisible to the programmer..
Can we get the remainder of a floating point division ?
Yes. Although the % operator fails to work on float numbers we can still get the remainder of floating point division by using a function fmod( ). The fmod( ) function divides the two float numbers passed to it as parameters and returns the remainder as a floating-point value. Following program shows fmod( ) function at work.
#include
main( )
{
printf ( “%f”, fmod ( 5.15, 3.0 ) ) ;
}
The above code snippet would give the output as 2.150000.
What does the error “Null Pointer Assignment” mean and what causes this error?
The Null Pointer Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of the data segment. In Borland’s C or C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice “Borland C++ - Copyright 1991 Borland Intl.”. In the small and medium memory models, a null pointer points to DS:0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment.
What’s the difference between a null pointer, a NULL macro, the ASCII NUL character and a null string?
A null pointer is a pointer which doesn’t point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn’t have any relationship with the null pointer. The null string is just another name for an empty string “”.
What is the difference between const char *p, char const *p, and char* const p ?
‘const char *p’ and ‘char const *p’ are the same, i.e. p points to a constant character. On the other hand, ‘char* const p’ means p is a constant pointer pointing to a character which means we cannot change the pointer p but we can change the character which p is pointing to.
How to get the memory size ?
Consider the following program
#include
#include
main( )
{
int memsize;
memsize = biosmemory( ) ;
printf ( “RAM size = %dK\n”,memsize ) ;
return 0 ;
}
The function biosmemory uses BIOS interrupt 0×12 to return the size of memory.
How to use function strdup( ) in a program?
The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmer’s responsibility to deallocate the memory using free( ).
#include
#include
#include
void main( )
{
char *str1, *str2 = “double”;
str1 = strdup ( str2 ) ;
printf ( “%s\n”, str1 ) ;
free ( str1 ) ;
}
Can we change the system date to some other date?
Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function.
#include
#include
void main( )
{
time_t tm ;
int d ;
tm = time ( NULL ) ;
printf ( “The System Date : %s”, ctime ( &tm ) ) ;
printf ( “\nHow many days ahead you want to set the date : ” ) ;
scanf ( “%d”, &d ) ;
tm += ( 24L * d ) * 60L * 60L ;
stime ( &tm ) ;
printf ( “\nNow the new date is : %s”, ctime ( &tm ) ) ;
}
In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time
How do I write a function that takes variable number of arguments?
The following program demonstrates this.
#include
#include
void main( )
{
int i = 10 ;
float f = 2.5 ;
char *str = “Hello!” ;
vfpf ( “%d %f %s\n”, i, f, str ) ;
vfpf ( “%s %s”, str, “Hi!” ) ;
}
void vfpf ( char *fmt, … )
{
va_list argptr ;
va_start ( argptr, fmt ) ;
vfprintf ( stdout, fmt, argptr ) ;
va_end ( argptr ) ;
}
Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return.
Can we get the process identification number of the current program?
Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro.
#include
#include
void main( )
{
printf ( “The process identification number of this program is %X\n”,
getpid( ) ) ;
}
How to obtain a path of the given file?
The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function.
#include “dir.h”
void main ( int argc, char *argv[] )
{
char *path ;
if ( path = searchpath ( argv[ 1 ] ) )
printf ( “Pathname : %s\n”, path ) ;
else
printf ( “File not found\n” ) ;
}
Can we get the x and y coordinate of the current cursor position ?
The function wherex( ) and wherey( ) returns the x-coordinate and y-coordinate of the current cursor position respectively. Both the functions return an integer value. The value returned by wherex( ) is the horizontal position of cursor and the value returned by wherey( ) is the vertical position of the cursor. Following program shows how to use the wherex( ) and wherey( ) functions.
#include
main( )
{
printf ( “Just\n To\n Test\n Where\n the cursor\n goes” ) ;
printf ( “Current location is X: %d Y: %d\n”, wherex( ), wherey( ) ) ;
}
How to obtain the current drive through C ?
We can use the function _getdrive( ) to obtain the current drive. The _getdrive( ) function uses DOS function 0X19 to get the current drive number
#include
main( )
{
int disk ;
disk = _getdrive( ) + ‘A’ - 1 ;
printf ( “The current drive is: %c\n”, disk ) ;
}
How to restrict the program’s output to a specific screen region?
A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string ‘Hello!’ gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window.
#include
main( )
{
int i, j ;
window ( 20, 8, 60, 17 ) ;
for ( i = 0 ; i < j =" 0">
How do I print the contents of environment variables?
The following program shows how to achieve this:
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( “\n%s”, env[ i++ ] ) ;
}
main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables.
What’s the difference between these two declarations?
struct str1 { … } ;
typedef struct { … } str2 ;
Ans : The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type — its users don’t necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.
How do I convert a floating-point number to a string?
Use function gcvt( ) to convert a floating-point number to a string. Following program demonstrates the use of this function.
#include
main( )
{
char str[25] ;
float no ;
int dg = 5 ; /* significant digits */
no = 14.3216 ;
gcvt ( no, dg, str ) ;
printf ( “String: %s\n”, str ) ;
}
How to find the row and column dimension of a given 2-D array?
Whenever we initialize a 2-D array at the same place where it has been declared, it is not necessary to mention the row dimension of an array. The row and column dimensions of such an array can be determined programmatically as shown in following program.
void main( )
{
int a[][3] = { 0, 1, 2,
9,-6, 8,
7, 5, 44,
23, 11,15 } ;
int c = sizeof ( a[0] ) / sizeof ( int ) ;
int r = ( sizeof ( a ) / sizeof ( int ) ) / c ;
int i, j ;
printf ( “\nRow: %d\nCol: %d\n”, r, c ) ;
for ( i = 0 ; i < j =" 0">
How do I write printf( ) so that the width of a field can be specified at runtime?
This is shown in following code snippet.
main( )
{
int w, no ;
printf ( “Enter number and the width for the
number field:” ) ;
scanf ( “%d%d”, &no, &w ) ;
printf ( “%*d”, w, no ) ;
}
Here, an ‘*’ in the format specifier in printf( ) indicates that an int value from the argument list should be used for the field width.
Are the following two statements identical?
char str[6] = “Kicit” ;
char *str = “Kicit” ;
Ans: No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known
by name str. In other words there is a location named str at which six characters are stored. The pointer declaration char *str ; on the other hand, requests a place that holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any contiguous array of chars, or nowhere.
How do I compare character data stored at two different memory locations?
Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.
#include
main( )
{
char *arr1 = “Kicit” ;
char *arr2 = “kicitNagpur” ;
int c ;
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( “\nStrings arr1 and arr2 compared using memcmp are identical” ) ;
else
printf ( “\nStrings arr1 and arr2 compared using memcmp are not identical”
) ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 )
printf ( “\nStrings arr1 and arr2 compared using memicmp are identical” )
;
else
printf ( “\nStrings arr1 and arr2 compared using memicmp are not
identical” ) ;
}
Sunday, October 12, 2008
INTERVIEW QUESTIONS & ANSWERS FROM C, C ++ part-III
Can math operations be performed on a void pointer?
No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of what it’s pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.
What is the difference between NULL and NUL?
NULL is a macro defined in for the null pointer.
NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There’s no standard macro NUL in C, but some people like to define it.
The digit 0 corresponds to a value of 80, decimal. Don’t confuse the digit 0 with the value of (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.
What are the advantages of the functions?
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are helpful in generalizing the program
Difference between arrays and pointers?
Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
Arrays use subscripted variables to access and manipulate data.Array variables can be equivalently written using pointer expression.
When should a far pointer be used?
Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.
What is static memory allocation and dynamic memory allocation?
Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.
What is a const pointer?
The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.
A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const (constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:
const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */
What is the purpose of realloc( )?
The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered.The second argument n specifies the new size.The size may be increased or decreased.If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( )
may create a new region and all the old data are moved to the new region.
How can you restore a redirected standard stream?
The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.
The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function.
What is Preprocessor?
The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.
How do you print an address?
The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*). Different compilers might print a pointer with different formats. Your compiler will pick a format that’s right for your environment.
If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:
printf( “%Pn”, (void*) buffer );
Is it possible to execute code even after the program exits the main() function?
The standard C library provides a function named atexit() that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.
How can I convert a number to a string?
The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa The following functions can be used to convert integers to strings:
Function Name Purpose
itoa() Converts an integer value to a string.
ltoa() Converts a long integer value to a string.
ultoa() Converts an unsigned long integer value to a string.
The following functions can be used to convert floating-point values to strings:
Function Name Purpose
ecvt() Converts a double-precision floating-point value to a string without an embedded decimal point.
fcvt() Same as ecvt(), but forces the precision to a specified number of digits.
gcvt() Converts a double-precision floating-point value to a string with an embedded decimal point.
How can I convert a string to a number?
The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose
atof() Converts a string to a double-precision floating-point value.
atoi() Converts a string to an integer.
atol() Converts a string to a long integer.
strtod() Converts a string to a double-precision floating-point value and reports any “leftover” numbers that could not be converted.
strtol() Converts a string to a long integer and reports any “leftover” numbers that could not be converted.
strtoul() Converts a string to an unsigned long integer and reports any “leftover” numbers that could not be converted.
What is a null pointer?
There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value
When should a type cast be used?
There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));
Can include files be nested?
Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored in
a precompiled state.
Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.
How can you check to see whether a symbol is defined?
You can use the #ifdef and #ifndef preprocessor directives to check whether a symbol has been defined (#ifdef) or whether it has not been defined (#ifndef).
How do you override a defined macro?
You can use the #undef preprocessor directive to undefine (override) a previously defined macro.
What is hashing?
To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.
The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.
If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.
To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.
One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. There are two ways to resolve this problem. In “open addressing,” the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its
hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found
The second method of resolving a hash collision is called “chaining.” In this method, a “bucket” or linked list holds all the elements whose keys hash to the same value.
When the hash table is searched, the list must be searched linearly.
What is the benefit of using an enum rather than a #define constant?
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the Programmer..
For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.
How’s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of what it’s pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.
What is the difference between NULL and NUL?
NULL is a macro defined in for the null pointer.
NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There’s no standard macro NUL in C, but some people like to define it.
The digit 0 corresponds to a value of 80, decimal. Don’t confuse the digit 0 with the value of (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.
What are the advantages of the functions?
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are helpful in generalizing the program
Difference between arrays and pointers?
Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
Arrays use subscripted variables to access and manipulate data.Array variables can be equivalently written using pointer expression.
When should a far pointer be used?
Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.
What is static memory allocation and dynamic memory allocation?
Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.
What is a const pointer?
The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.
A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const (constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:
const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */
What is the purpose of realloc( )?
The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered.The second argument n specifies the new size.The size may be increased or decreased.If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( )
may create a new region and all the old data are moved to the new region.
How can you restore a redirected standard stream?
The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.
The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function.
What is Preprocessor?
The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.
How do you print an address?
The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*). Different compilers might print a pointer with different formats. Your compiler will pick a format that’s right for your environment.
If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:
printf( “%Pn”, (void*) buffer );
Is it possible to execute code even after the program exits the main() function?
The standard C library provides a function named atexit() that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.
How can I convert a number to a string?
The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa The following functions can be used to convert integers to strings:
Function Name Purpose
itoa() Converts an integer value to a string.
ltoa() Converts a long integer value to a string.
ultoa() Converts an unsigned long integer value to a string.
The following functions can be used to convert floating-point values to strings:
Function Name Purpose
ecvt() Converts a double-precision floating-point value to a string without an embedded decimal point.
fcvt() Same as ecvt(), but forces the precision to a specified number of digits.
gcvt() Converts a double-precision floating-point value to a string with an embedded decimal point.
How can I convert a string to a number?
The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose
atof() Converts a string to a double-precision floating-point value.
atoi() Converts a string to an integer.
atol() Converts a string to a long integer.
strtod() Converts a string to a double-precision floating-point value and reports any “leftover” numbers that could not be converted.
strtol() Converts a string to a long integer and reports any “leftover” numbers that could not be converted.
strtoul() Converts a string to an unsigned long integer and reports any “leftover” numbers that could not be converted.
What is a null pointer?
There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value
When should a type cast be used?
There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));
Can include files be nested?
Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored in
a precompiled state.
Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.
How can you check to see whether a symbol is defined?
You can use the #ifdef and #ifndef preprocessor directives to check whether a symbol has been defined (#ifdef) or whether it has not been defined (#ifndef).
How do you override a defined macro?
You can use the #undef preprocessor directive to undefine (override) a previously defined macro.
What is hashing?
To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.
The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.
If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.
To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.
One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. There are two ways to resolve this problem. In “open addressing,” the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its
hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found
The second method of resolving a hash collision is called “chaining.” In this method, a “bucket” or linked list holds all the elements whose keys hash to the same value.
When the hash table is searched, the list must be searched linearly.
What is the benefit of using an enum rather than a #define constant?
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the Programmer..
For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.
How’s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
Subscribe to:
Posts (Atom)